﻿using AutoMapper;
using Dapper;
using DocumentFormat.OpenXml.Bibliography;
using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.Math;
using DocumentFormat.OpenXml.Office2010.ExcelAc;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Wordprocessing;
using Hangfire;
using Hangfire.LiteDB;
using housingsafety.server.Caching.Core;
using housingsafety.server.Entities;
using housingsafety.server.Entities.DataModels;
using housingsafety.server.Helpers;
using housingsafety.server.Models;
using housingsafety.server.Repository;
using housingsafety.server.Repository.Extensions;
using housingsafety.server.Svcs;
using KS3;
using KS3.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Minio.DataModel;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Npgsql;
using NPOI.HPSF;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Org.BouncyCastle.Asn1.Ocsp;
using Quartz.Util;
using RestSharp.Extensions;
using SelfBuiltHouseSafety.Models;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace housingsafety.server.Controllers
{
    /// <summary>
    /// 房屋管理服务
    /// </summary>
    public class HouseMngSqjzController : BaseController<HouseMngController>
    {
        public IConfiguration Configuration { get; }
        private readonly ICache _cache;
        private readonly IMapper _mapper;
        private readonly IStorageProvider _storageProvider;
        private readonly ZmDbContext _dbContext;
        private readonly IRepository<ZmUser> _userRepository;
        private readonly IRepository<ZmBuildings> _buildingRepository;
        private readonly IRepository<ZmFileAttach> _fileAttachRepository;
        private readonly IOptions<StaticDataConf> _staticVtOptions;
        private readonly IRepository<ZmDepartment> _departmentRepository;
        private readonly IRepository<ZmPcYhLogDx> _zmPcYhLogDxRepository;
        private readonly IRepository<ZmPcYhLog> _zmPcYhLogRepository;
        private readonly IRepository<ZmPcYh> _zmPcYhRepository;
        private readonly IRepository<ZmPcBase> _zmPcBaseRepository;
        private readonly IRepository<ZmPcBaseLog> _zmPcBaseLogRepository;

        private readonly IDbTransaction _transaction;

        private readonly Microsoft.AspNetCore.Http.Features.FormOptions _defaultFormOptions = new Microsoft.AspNetCore.Http.Features.FormOptions();
        private readonly string[] _permittedExtensions = { ".mp3", ".mp4", ".jpg", ".jpeg", ".png", ".geojson", ".doc", ".docx" };

        private static object _lock = new object();

        private readonly KS3Client _kS3Client;


        public HouseMngSqjzController(IStorageProvider storageProvider
            , KS3Client kS3Client
            , IRepository<ZmPcYh> zmPcYhRepository
            , IRepository<ZmPcYhLog> zmPcYhLogRepository
            , IRepository<ZmPcYhLogDx> zmPcYhLogDxRepository
            , IRepository<ZmDepartment> departmentRepository
            , IRepository<ZmUser> userRepository
            , IRepository<ZmFileAttach> fileAttachRepository
            , IMapper mapper, ICacheProvider cacheProvider, ZmDbContext dbContext
            , IOptions<StaticDataConf> staticVtOptions
            , ILogger<HouseMngController> logger,
            IConfiguration configuration
            , IRepository<ZmSystemLog> systemLogRepository, IRepository<ZmBuildings> buildingRepository, IRepository<ZmPcBase> zmPcBaseRepository, IRepository<ZmPcBaseLog> zmPcBaseLogRepository) : base(logger, systemLogRepository)
        {
            _kS3Client = kS3Client;
            _zmPcYhRepository = zmPcYhRepository;
            _zmPcYhLogRepository = zmPcYhLogRepository;
            _zmPcYhLogDxRepository = zmPcYhLogDxRepository;
            _zmPcBaseLogRepository = zmPcBaseLogRepository;
            _zmPcBaseRepository = zmPcBaseRepository;
            _buildingRepository = buildingRepository;
            _storageProvider = storageProvider;
            _mapper = mapper;
            _dbContext = dbContext;
            _cache = cacheProvider.CreateCache();
            _userRepository = userRepository;
            _fileAttachRepository = fileAttachRepository;
            _staticVtOptions = staticVtOptions;
            _departmentRepository = departmentRepository;
            Configuration = configuration;

        }

        /// <summary>
        ///根据用户编号获取用户账号信息
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("housessqjz/search-attr")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<ZmUserdto2>), 200)]
        public RespRet<ZmUserdto2> GetBuildingsByFwbh()
        {
            try
            {
                var userNumber = this.CurrentUser();
                if (string.IsNullOrEmpty(userNumber))
                {
                    return new RespRet<ZmUserdto2>(false, "user not logined");
                }
                var user = _dbContext.ZmUser.FirstOrDefault(u => u.Number == userNumber && u.IsDelete != 1 && u.Disabled != 1);
                if (null == user)
                {
                    var res = new RespRet<ZmUserdto2>(false, "账号不存在");
                    WriteSystemLog("housessqjz/search-attr", res, userNumber);
                    return res;
                }
                var a = JsonRegion(user.District);
                if (a == null)
                {
                    var res = new RespRet<ZmUserdto2>(false, "未有管辖区，请确认账号信息");
                    WriteSystemLog("housessqjz/search-attr", res, userNumber);
                    return res;
                }
                JObject obj = JObject.Parse(user.District);
                string RegionCode = (string)obj["RegionCode"];
                var departments = _cache.Get("departments") as List<ZmDepartment>;
                if (null == departments)
                {
                    departments = _departmentRepository.Query().ToList();
                    _cache.Set("departments", departments);
                }
                var len = RegionCode.Substring(RegionCode.Length - 3) == "000" ? RegionCode.Length - 3 : RegionCode.Length;
                var data = new ZmUserdto2
                {
                    NickName = user.Nickname,
                    Uname = user.Uname
                };
                data.Roletype = user.RoleType;
                data.City = "北京市";
                data.Citydm = "110000";
                if (len == 6)
                {
                    var find3 = departments.Find(_ => _.RegionCode == RegionCode.Substring(0, Math.Min(6, RegionCode.Length)));
                    data.Xzq = find3?.RegionName;
                    data.Xzqdm = find3?.RegionCode;
                }
                if (len == 9)
                {
                    var find3 = departments.Find(_ => _.RegionCode == RegionCode.Substring(0, Math.Min(6, RegionCode.Length)));
                    data.Xzq = find3?.RegionName;
                    data.Xzqdm = find3?.RegionCode;
                    var find4 = departments.Find(_ => _.RegionCode == (RegionCode.Substring(0, Math.Min(9, RegionCode.Length)) + "000"));
                    data.Town = find4?.RegionName;
                    data.Towndm = find4?.RegionCode;
                }
                if (len == 12)
                {
                    var find3 = departments.Find(_ => _.RegionCode == RegionCode.Substring(0, Math.Min(6, RegionCode.Length)));
                    data.Xzq = find3?.RegionName;
                    data.Xzqdm = find3?.RegionCode;
                    var find4 = departments.Find(_ => _.RegionCode == (RegionCode.Substring(0, Math.Min(9, RegionCode.Length)) + "000"));
                    data.Town = find4?.RegionName;
                    data.Towndm = find4?.RegionCode;
                    var find5 = departments.Find(_ => _.RegionCode == RegionCode);
                    data.Village = find5?.RegionName;
                    data.Villagedm = find5?.RegionCode;
                }
                var r = new RespRet<ZmUserdto2>(true, "Ok", data);
                WriteSystemLog("housessqjz/search-attr", r, userNumber);
                return r;
            }
            catch (Exception ex)
            {
                var res = new RespRet<ZmUserdto2>(false, ex.ToString());
                WriteSystemLogError("housessqjz/search-attr", res, null);
                res.Msg = "系统异常";
                return res;
            }
        }



        /// <summary>
        ///根据房屋编号查找房屋基本信息
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("housessqjz/search-attrbyfwbh")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<ZmBuildingsDto>), 200)]
        public RespRet<ZmBuildingsDto> GetBuildingsByFwbhcj([FromQuery] string fwbh)
        {
            try
            {
                var userNumber = this.CurrentUser();
                if (string.IsNullOrEmpty(userNumber))
                {
                    return new RespRet<ZmBuildingsDto>(false, "user not logined");
                }
                if (string.IsNullOrEmpty(fwbh))
                {
                    return new RespRet<ZmBuildingsDto>(false, "房屋编号不能为空");
                }
                var sbSql = new StringBuilder();
                var sbSqlWhere = new StringBuilder();
                var sqlParams = new List<NpgsqlParameter>();
                sbSql.Append($@"select  * FROM zm_buildings a   ");
                sbSqlWhere.Append($@" a.Fwbh = @Fwbh and");
                sqlParams.Add(new NpgsqlParameter("Fwbh", $"{fwbh}"));
                if (!string.IsNullOrEmpty(sbSqlWhere.ToString()))
                {
                    sbSql.Append($@" where {sbSqlWhere} 1=1 ");
                }
                var count = _dbContext.ZmBuildingsDto.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).Count();
                if (count < 1)
                {
                }
                var datas = _dbContext.ZmBuildingsDto.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).FirstOrDefault();
                if (datas == null)
                {
                    var res = new RespRet<ZmBuildingsDto>(false, "未找到房屋信息");
                    WriteSystemLog("housessqjz/search-attr", res, userNumber);
                    return res;
                }
                var departments = _cache.Get("departments") as List<ZmDepartment>;
                if (null == departments)
                {
                    departments = _departmentRepository.Query().ToList();
                    _cache.Set("departments", departments);
                }
                var find3 = departments.Find(_ => _.RegionCode == datas.Xzqdm);
                datas.XzqdmAlias = find3?.RegionName;
                var find4 = departments.Find(_ => _.RegionCode == datas.Towndm);
                datas.TownAlias = find4?.RegionName;
                var find5 = departments.Find(_ => _.RegionCode == datas.Villagedm);
                datas.VillageAlias = find5?.RegionName;
                var r = new RespRet<ZmBuildingsDto>(true, "Ok", datas);
                WriteSystemLog("housessqjz/search-attr", r, userNumber);
                return r;
            }
            catch (Exception ex)
            {
                var res = new RespRet<ZmBuildingsDto>(false, ex.ToString());
                WriteSystemLogError("housessqjz/search-attr", res, null);
                res.Msg = "系统异常";
                return res;
            }
        }





        /// <summary>
        /// 根据房屋编号获取房屋采集信息
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("housessqjz/search-attrpc")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<ZmPcBaseSqjz>), 200)]
        public new RespRet<object> SearchAttrList2([FromQuery] string fwbh)
        {
            var userNumber = this.CurrentUser();
            var user = _dbContext.ZmUser.FirstOrDefault(u => u.Number == userNumber && u.IsDelete != 1 && u.Disabled != 1);
            try
            {
                if (string.IsNullOrEmpty(userNumber))
                {
                    return new RespRet<object>(false, "user not logined");
                }
                if (string.IsNullOrEmpty(fwbh))
                {
                    return new RespRet<object>(false, "房屋编号不能为空");
                }
                var sbSql = new StringBuilder();
                var sbSqlWhere = new StringBuilder();
                var sqlParams = new List<NpgsqlParameter>();
                sbSql.Append($@"select *  FROM zm_pc_base_sqjz    ");
                sbSqlWhere.Append($@" Fwbh = @Fwbh and yhly=@yhly and ");
                //需要判断第一次设置的状态不为空
                sbSqlWhere.Append($@"  fwbh in (select fwbh  FROM zm_pc_baselog_sqjz  where Fwbh =@Fwbh and yhly=@yhly and fwzt is null) and ");
                sqlParams.Add(new NpgsqlParameter("Fwbh", $"{fwbh}"));
                sqlParams.Add(new NpgsqlParameter("yhly", user.RoleType));
                if (!string.IsNullOrEmpty(sbSqlWhere.ToString()))
                {
                    sbSql.Append($@" where {sbSqlWhere} 1=1 ");
                }
                //var count = _dbContext.ZmPcBaseSqjz.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).Count();

                var isdb = "";
                var zclog = _dbContext.ZmPcBase.Where(c => c.Fwbh == fwbh).FirstOrDefault();
                if (zclog != null)
                {
                    isdb = zclog.Jsrysstd;
                }
                var datas = _dbContext.ZmPcBaseSqjz.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).FirstOrDefault();
           



                if (datas == null)
                {
                    //此角色人员未进行核验，或核验状态均为不出租和已拆除，需要把状态给到自查
                    var baseSqjz = _dbContext.ZmPcBaseSqjz.Where(c => c.Fwbh == fwbh).FirstOrDefault();
                    sbSql = new StringBuilder();
                    sbSql.Append($@" select *  FROM zm_pc_base where Fwbh = @Fwbh  ");
                    var zmpcbase = _dbContext.ZmPcBase.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).FirstOrDefault();
                    if (zmpcbase == null)
                    {
                        var Building = _dbContext.ZmBuildings.FirstOrDefault(c => c.Fwbh == fwbh);
                        if (Building == null)
                        {
                            var res = new RespRet<object>(false, "未找到房屋信息", new { data = datas, Jsrysstd = isdb });
                            WriteSystemLog("housessqjz/search-attrpc", res, fwbh);
                            return res;
                        }
                        datas = _mapper.Map<ZmPcBaseSqjz>(Building);
                    }
                    else
                    {
                        zmpcbase.Jsrysstd = zmpcbase.Tdsfdb;
                        datas = _mapper.Map<ZmPcBaseSqjz>(zmpcbase);
                    }
                    if (baseSqjz != null)
                    {
                        datas.Fwzt = baseSqjz.Fwzt;
                    }
                }
                datas.SfmzstdPhoto = null;
                datas.SfczjxgbczzrPhoto = null;
                datas.SstdsyyrkrclzxPhoto = null;
                datas.GryssdcsszblyyqksddpPhoto = null;
                datas.FwyfwdddzxccdsssfayqjshsfPhoto = null;

                var r = new RespRet<object>(true, "Ok", new { data = datas, Jsrysstd = isdb });
                WriteSystemLog("housessqjz/search-attrpc", r, fwbh);
                return r;
            }
            catch (Exception ex)
            {
                WriteSystemLogError("housessqjz/search-attrpc", new RespRet<ZmPcBaseSqjz>(false, ex.ToString()), fwbh);
                return new RespRet<object>(false, "系统异常");
            }
        }



        /// <summary>
        /// 根据自查记录详情
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("housessqjz/search-yhlogdetaile")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<object> Yhlogdetaile([FromQuery] string fwbh)
        {
            var userNumber = this.CurrentUser();
            try
            {

                if (string.IsNullOrEmpty(userNumber))
                {
                    return new RespRet<object>(false, "user not logined");
                }
                var sbSql = new StringBuilder();
                var sbSqlWhere = new StringBuilder();
                var sqlParams = new List<NpgsqlParameter>();

                sbSql.Append($@"select *  FROM zm_pc_yh    ");

                sbSqlWhere.Append($@" fwbh = @fwbh and");
                sqlParams.Add(new NpgsqlParameter("fwbh", $"{fwbh}"));

                if (!string.IsNullOrEmpty(sbSqlWhere.ToString()))
                {
                    sbSql.Append($@" where {sbSqlWhere} 1=1 ");
                }
                var from = _dbContext.ZmPcYh.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).FirstOrDefault();
                if (from == null)
                {

                    var res = new RespRet<object>(false, "未找到自查记录", from);
                    WriteSystemLog("housessqjz/search-yhlogdetaile", res, fwbh);
                    return res;
                }
                from.UseElectricBicyclePhoto = from.UseElectricBicyclePhoto == null ? null : string.Join("|", JsonStr2List(from.UseElectricBicyclePhoto));
                from.UseBottledLiquefiedGasPhoto = from.UseBottledLiquefiedGasPhoto == null ? null : string.Join("|", JsonStr2List(from.UseBottledLiquefiedGasPhoto));
                from.UseStackedItemsPhoto = from.UseStackedItemsPhoto == null ? null : string.Join("|", JsonStr2List(from.UseStackedItemsPhoto));
                from.SlljdxPhoto = from.SlljdxPhoto == null ? null : string.Join("|", JsonStr2List(from.SlljdxPhoto));


                from.YgbjwfwhyxPhoto = from.YgbjwfwhyxPhoto == null ? null : string.Join("|", JsonStr2List(from.YgbjwfwhyxPhoto));
                from.MhqwbcwhyxPhoto = from.MhqwbcwhyxPhoto == null ? null : string.Join("|", JsonStr2List(from.MhqwbcwhyxPhoto));
                from.JyplmhxtwbcwhyxPhoto = from.JyplmhxtwbcwhyxPhoto == null ? null : string.Join("|", JsonStr2List(from.JyplmhxtwbcwhyxPhoto));
                from.UseElectricBicycleZgPhoto = from.UseElectricBicycleZgPhoto == null ? null : string.Join("|", JsonStr2List(from.UseElectricBicycleZgPhoto));
                from.UseBottledLiquefiedGasZgPhoto = from.UseBottledLiquefiedGasZgPhoto == null ? null : string.Join("|", JsonStr2List(from.UseBottledLiquefiedGasZgPhoto));
                from.UseStackedItemsZgPhoto = from.UseStackedItemsZgPhoto == null ? null : string.Join("|", JsonStr2List(from.UseStackedItemsZgPhoto));
                from.SlljdxZgPhoto = from.SlljdxZgPhoto == null ? null : string.Join("|", JsonStr2List(from.SlljdxZgPhoto));
                from.YgbjwfwhyxMsgZgPhoto = from.YgbjwfwhyxMsgZgPhoto == null ? null : string.Join("|", JsonStr2List(from.YgbjwfwhyxMsgZgPhoto));
                from.MhqwbcwhyxZgPhoto = from.MhqwbcwhyxZgPhoto == null ? null : string.Join("|", JsonStr2List(from.MhqwbcwhyxZgPhoto));
                from.JyplmhxtwbcwhyxZgPhoto = from.JyplmhxtwbcwhyxZgPhoto == null ? null : string.Join("|", JsonStr2List(from.JyplmhxtwbcwhyxZgPhoto));
                //返回采集信息
                var ZmPcBase = _dbContext.ZmPcBase.FirstOrDefault(u => u.Fwbh == from.Fwbh && u.IsDelete != 1);

                var r = new RespRet<object>(true, "Ok", new { ZmPcBase = ZmPcBase, ZmPcYh = from });
                WriteSystemLog("housessqjz/search-yhlogdetaile", r, userNumber);
                return r;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                WriteSystemLogError("housessqjz/search-yhlogdetaile", res, fwbh);
                res.Msg = "系统异常";
                return res;
            }
        }


        /// <summary>
        /// 根据自查记录详情
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("housessqjz/search-yhlogdetaileall")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<object> YhlogdetaileAll([FromQuery] string id)
        {
            // var userNumber = this.CurrentUser();
            try
            {
                var userNumber = this.CurrentUser();
                var user = _dbContext.ZmUser.FirstOrDefault(u => u.Number == userNumber && u.IsDelete != 1 && u.Disabled != 1);
                //if (string.IsNullOrEmpty(userNumber))
                //{
                //    return new RespRet<object>(false, "user not logined");
                //}
                var sbSql = new StringBuilder();
                var sbSqlWhere = new StringBuilder();
                var sqlParams = new List<NpgsqlParameter>();

                sbSql.Append($@"select *  FROM zm_pc_yhlog_sqjz    ");

                sbSqlWhere.Append($@" id = @fwbh and base_id in (select id from zm_pc_baselog_sqjz where id=base_id )and");
                sqlParams.Add(new NpgsqlParameter("fwbh", $"{id}"));
                sqlParams.Add(new NpgsqlParameter("yhly", user.RoleType));
                if (!string.IsNullOrEmpty(sbSqlWhere.ToString()))
                {
                    sbSql.Append($@" where {sbSqlWhere} 1=1 ");
                }
                var from = _dbContext.ZmPcYhLogSqjz.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).FirstOrDefault();
                if (from == null)
                {
                    sbSql = new StringBuilder();
                    sbSqlWhere = new StringBuilder();
                    sqlParams = new List<NpgsqlParameter>();

                    sbSql.Append($@"select *  FROM zm_pc_yhlog    ");

                    sbSqlWhere.Append($@" id = @fwbh and");
                    sqlParams.Add(new NpgsqlParameter("fwbh", $"{id}"));

                    if (!string.IsNullOrEmpty(sbSqlWhere.ToString()))
                    {
                        sbSql.Append($@" where {sbSqlWhere} 1=1 ");
                    }
                    var yhlog = _dbContext.ZmPcYhLog.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).FirstOrDefault();

                    if (yhlog == null)
                    {
                        var res = new RespRet<object>(false, "未找到记录", yhlog);
                        WriteSystemLog("housessqjz/search-yhlogdetaileall", res, id);
                        return res;
                    }
                    yhlog.UseElectricBicyclePhoto = yhlog.UseElectricBicyclePhoto == null ? null : string.Join("|", JsonStr2List(yhlog.UseElectricBicyclePhoto));
                    yhlog.UseBottledLiquefiedGasPhoto = yhlog.UseBottledLiquefiedGasPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.UseBottledLiquefiedGasPhoto));
                    yhlog.UseStackedItemsPhoto = yhlog.UseStackedItemsPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.UseStackedItemsPhoto));
                    yhlog.SlljdxPhoto = yhlog.SlljdxPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.SlljdxPhoto));
                    yhlog.YgbjwfwhyxPhoto = yhlog.YgbjwfwhyxPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.YgbjwfwhyxPhoto));
                    yhlog.MhqwbcwhyxPhoto = yhlog.MhqwbcwhyxPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.MhqwbcwhyxPhoto));
                    yhlog.JyplmhxtwbcwhyxPhoto = yhlog.JyplmhxtwbcwhyxPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.JyplmhxtwbcwhyxPhoto));
                    yhlog.UseElectricBicycleZgPhoto = yhlog.UseElectricBicycleZgPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.UseElectricBicycleZgPhoto));
                    yhlog.UseBottledLiquefiedGasZgPhoto = yhlog.UseBottledLiquefiedGasZgPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.UseBottledLiquefiedGasZgPhoto));
                    yhlog.UseStackedItemsZgPhoto = yhlog.UseStackedItemsZgPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.UseStackedItemsZgPhoto));
                    yhlog.SlljdxZgPhoto = yhlog.SlljdxZgPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.SlljdxZgPhoto));
                    yhlog.YgbjwfwhyxMsgZgPhoto = yhlog.YgbjwfwhyxMsgZgPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.YgbjwfwhyxMsgZgPhoto));
                    yhlog.MhqwbcwhyxZgPhoto = yhlog.MhqwbcwhyxZgPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.MhqwbcwhyxZgPhoto));
                    yhlog.JyplmhxtwbcwhyxZgPhoto = yhlog.JyplmhxtwbcwhyxZgPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.JyplmhxtwbcwhyxZgPhoto));

                    //返回采集信息
                    var ZmPcBase = _dbContext.ZmPcBaselog.FirstOrDefault(u => u.Id == yhlog.BaseId && u.IsDelete != 1);

                    var re = new RespRet<object>(true, "Ok", new { ZmPcBase = ZmPcBase, ZmPcYh = yhlog });
                    WriteSystemLog("housessqjz/search-yhlogdetaileall", re, null);
                    return re;

                }
                from.UseElectricBicyclePhoto = from.UseElectricBicyclePhoto == null ? null : string.Join("|", JsonStr2List(from.UseElectricBicyclePhoto));
                from.UseBottledLiquefiedGasPhoto = from.UseBottledLiquefiedGasPhoto == null ? null : string.Join("|", JsonStr2List(from.UseBottledLiquefiedGasPhoto));
                from.UseStackedItemsPhoto = from.UseStackedItemsPhoto == null ? null : string.Join("|", JsonStr2List(from.UseStackedItemsPhoto));
                from.SlljdxPhoto = from.SlljdxPhoto == null ? null : string.Join("|", JsonStr2List(from.SlljdxPhoto));


                from.YgbjwfwhyxPhoto = from.YgbjwfwhyxPhoto == null ? null : string.Join("|", JsonStr2List(from.YgbjwfwhyxPhoto));
                from.MhqwbcwhyxPhoto = from.MhqwbcwhyxPhoto == null ? null : string.Join("|", JsonStr2List(from.MhqwbcwhyxPhoto));
                from.JyplmhxtwbcwhyxPhoto = from.JyplmhxtwbcwhyxPhoto == null ? null : string.Join("|", JsonStr2List(from.JyplmhxtwbcwhyxPhoto));
                from.UseElectricBicycleZgPhoto = from.UseElectricBicycleZgPhoto == null ? null : string.Join("|", JsonStr2List(from.UseElectricBicycleZgPhoto));
                from.UseBottledLiquefiedGasZgPhoto = from.UseBottledLiquefiedGasZgPhoto == null ? null : string.Join("|", JsonStr2List(from.UseBottledLiquefiedGasZgPhoto));
                from.UseStackedItemsZgPhoto = from.UseStackedItemsZgPhoto == null ? null : string.Join("|", JsonStr2List(from.UseStackedItemsZgPhoto));
                from.SlljdxZgPhoto = from.SlljdxZgPhoto == null ? null : string.Join("|", JsonStr2List(from.SlljdxZgPhoto));
                from.YgbjwfwhyxMsgZgPhoto = from.YgbjwfwhyxMsgZgPhoto == null ? null : string.Join("|", JsonStr2List(from.YgbjwfwhyxMsgZgPhoto));
                from.MhqwbcwhyxZgPhoto = from.MhqwbcwhyxZgPhoto == null ? null : string.Join("|", JsonStr2List(from.MhqwbcwhyxZgPhoto));
                from.JyplmhxtwbcwhyxZgPhoto = from.JyplmhxtwbcwhyxZgPhoto == null ? null : string.Join("|", JsonStr2List(from.JyplmhxtwbcwhyxZgPhoto));
                //返回采集信息
                var ZmPcBasecj = _dbContext.ZmPcBaseLogSqjz.FirstOrDefault(u => u.Id == from.BaseId && u.IsDelete != 1);

                ZmPcBasecj.SfmzstdPhoto = (ZmPcBasecj.SfmzstdPhoto == null || ZmPcBasecj.SfmzstdPhoto == "")  ? null : string.Join("|", JsonStr2List(ZmPcBasecj.SfmzstdPhoto));

                ZmPcBasecj.SfczjxgbczzrPhoto = (ZmPcBasecj.SfczjxgbczzrPhoto == null || ZmPcBasecj.SfczjxgbczzrPhoto == "") ? null : string.Join("|", JsonStr2List(ZmPcBasecj.SfczjxgbczzrPhoto));


                ZmPcBasecj.SstdsyyrkrclzxPhoto = (ZmPcBasecj.SstdsyyrkrclzxPhoto == null || ZmPcBasecj.SstdsyyrkrclzxPhoto == "") ? null : string.Join("|", JsonStr2List(ZmPcBasecj.SstdsyyrkrclzxPhoto));
                ZmPcBasecj.GryssdcsszblyyqksddpPhoto = (ZmPcBasecj.GryssdcsszblyyqksddpPhoto == null || ZmPcBasecj.GryssdcsszblyyqksddpPhoto == "") ? null : string.Join("|", JsonStr2List(ZmPcBasecj.GryssdcsszblyyqksddpPhoto));

                ZmPcBasecj.FwyfwdddzxccdsssfayqjshsfPhoto = (ZmPcBasecj.FwyfwdddzxccdsssfayqjshsfPhoto == null || ZmPcBasecj.FwyfwdddzxccdsssfayqjshsfPhoto == "") ? null : string.Join("|", JsonStr2List(ZmPcBasecj.FwyfwdddzxccdsssfayqjshsfPhoto));


                var r = new RespRet<object>(true, "Ok", new { ZmPcBase = ZmPcBasecj, ZmPcYh = from });
                WriteSystemLog("housessqjz/search-yhlogdetaileall", r, null);
                return r;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                WriteSystemLogError("housessqjz/search-yhlogdetaileall", res, id);
                res.Msg = "系统异常";
                return res;
            }
        }



        /// <summary>
        /// 根据id获取检查记录详情
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("housessqjz/search-cjyhlogdetaile")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<object> YhlogdetaileCj([FromQuery] string id)
        {
            var userNumber = this.CurrentUser();
            var user = _dbContext.ZmUser.FirstOrDefault(u => u.Number == userNumber && u.IsDelete != 1 && u.Disabled != 1);
            try
            {

                if (string.IsNullOrEmpty(userNumber))
                {
                    return new RespRet<object>(false, "user not logined");
                }
                var sbSql = new StringBuilder();
                var sbSqlWhere = new StringBuilder();
                var sqlParams = new List<NpgsqlParameter>();

                sbSql.Append($@"select *  FROM zm_pc_yh_sqjz    ");

                sbSqlWhere.Append($@" id = @fwbh and yhly=@yhly and ");
                sqlParams.Add(new NpgsqlParameter("fwbh", $"{id}"));
                sqlParams.Add(new NpgsqlParameter("yhly", $"{user.RoleType}"));
                if (!string.IsNullOrEmpty(sbSqlWhere.ToString()))
                {
                    sbSql.Append($@" where {sbSqlWhere} 1=1 ");
                }
                var from = _dbContext.ZmPcYhCj.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).FirstOrDefault();
                if (from == null)
                {
                    var res = new RespRet<object>(false, "未找到自查记录，请传递正确房屋编号", from);
                    WriteSystemLog("housessqjz/search-yhlogdetaile", res, id);
                    return res;
                }
                from.UseElectricBicyclePhoto = from.UseElectricBicyclePhoto == null ? null : string.Join("|", JsonStr2List(from.UseElectricBicyclePhoto));
                from.UseBottledLiquefiedGasPhoto = from.UseBottledLiquefiedGasPhoto == null ? null : string.Join("|", JsonStr2List(from.UseBottledLiquefiedGasPhoto));
                from.UseStackedItemsPhoto = from.UseStackedItemsPhoto == null ? null : string.Join("|", JsonStr2List(from.UseStackedItemsPhoto));
                from.SlljdxPhoto = from.SlljdxPhoto == null ? null : string.Join("|", JsonStr2List(from.SlljdxPhoto));
                from.YgbjwfwhyxPhoto = from.YgbjwfwhyxPhoto == null ? null : string.Join("|", JsonStr2List(from.YgbjwfwhyxPhoto));
                from.MhqwbcwhyxPhoto = from.MhqwbcwhyxPhoto == null ? null : string.Join("|", JsonStr2List(from.MhqwbcwhyxPhoto));
                from.JyplmhxtwbcwhyxPhoto = from.JyplmhxtwbcwhyxPhoto == null ? null : string.Join("|", JsonStr2List(from.JyplmhxtwbcwhyxPhoto));
                from.UseElectricBicycleZgPhoto = from.UseElectricBicycleZgPhoto == null ? null : string.Join("|", JsonStr2List(from.UseElectricBicycleZgPhoto));
                from.UseBottledLiquefiedGasZgPhoto = from.UseBottledLiquefiedGasZgPhoto == null ? null : string.Join("|", JsonStr2List(from.UseBottledLiquefiedGasZgPhoto));
                from.UseStackedItemsZgPhoto = from.UseStackedItemsZgPhoto == null ? null : string.Join("|", JsonStr2List(from.UseStackedItemsZgPhoto));
                from.SlljdxZgPhoto = from.SlljdxZgPhoto == null ? null : string.Join("|", JsonStr2List(from.SlljdxZgPhoto));
                from.YgbjwfwhyxPhoto = from.YgbjwfwhyxPhoto == null ? null : string.Join("|", JsonStr2List(from.YgbjwfwhyxPhoto));
                from.MhqwbcwhyxZgPhoto = from.MhqwbcwhyxZgPhoto == null ? null : string.Join("|", JsonStr2List(from.MhqwbcwhyxZgPhoto));
                from.JyplmhxtwbcwhyxZgPhoto = from.JyplmhxtwbcwhyxZgPhoto == null ? null : string.Join("|", JsonStr2List(from.JyplmhxtwbcwhyxZgPhoto));
                //返回采集信息
                var ZmPcBase = _dbContext.ZmPcBaseSqjz.FirstOrDefault(u => u.Id == from.BaseId && u.IsDelete != 1);

                var r = new RespRet<object>(true, "Ok", new { ZmPcBaseCj = ZmPcBase, ZmPcYhCj = from });
                WriteSystemLog("housessqjz/search-yhlogdetaile", r, userNumber);
                return r;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                WriteSystemLogError("housessqjz/search-yhlogdetaile", res, id);
                res.Msg = "系统异常";
                return res;
            }
        }

        private List<string> JsonStr2List(string jsonStr)
        {
            try
            {
                return JsonConvert.DeserializeObject<List<string>>(jsonStr);
            }
            catch (System.Exception)
            {
            }

            return null;
        }


        private object JsonRegion(string jsonStr)
        {
            try
            {
                return JsonConvert.DeserializeObject<object>(jsonStr);
            }
            catch (System.Exception)
            {
            }

            return null;
        }

        /// <summary>
        /// 自查记录
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("housessqjz/searchcj-attryhzclog")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<ZmPcYhLogAllDto2>>), 200)]
        public RespRet<Page<ZmPcYhLogAllDto2>> attrzclog([FromBody] PageHouseRequestInputCj pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<ZmPcYhLogAllDto2>>(false, "PageIndex must >= 0");
            }
            var userNumber = this.CurrentUser();
            var user = _dbContext.ZmUser.FirstOrDefault(u => u.Number == userNumber && u.IsDelete != 1 && u.Disabled != 1);
            //if (string.IsNullOrEmpty(userNumber))
            //{
            //    return new RespRet<Page<ZmPcYhLogAllDto2>>(false, "user not logined");
            //}
            try
            {
                var sbSql = new StringBuilder();
                var sbSqlWhere = new StringBuilder();
                var sbSqlWhere2 = new StringBuilder();
                var sqlParams = new List<NpgsqlParameter>();
                if (!string.IsNullOrWhiteSpace(pageRequest.Villagedm))
                {
                    sbSqlWhere.Append($@" and a.villagedm like @villagedm ");
                    sqlParams.Add(new NpgsqlParameter("villagedm", $"{"%" + pageRequest.Villagedm + "%"}"));
                }
                if (!string.IsNullOrWhiteSpace(pageRequest.Towndm))
                {
                    sbSqlWhere.Append($@" and a.Towndm like @Towndm ");
                    sqlParams.Add(new NpgsqlParameter("Towndm", $"{"%" + pageRequest.Towndm + "%"}"));
                }
                if (!string.IsNullOrWhiteSpace(pageRequest.Xzqdm))
                {
                    sbSqlWhere.Append($@" and a.Xzqdm like @Xzqdm ");
                    sqlParams.Add(new NpgsqlParameter("Xzqdm", $"{"%" + pageRequest.Xzqdm + "%"}"));
                }
                if (pageRequest.Pczt >= 1)
                {
                    sbSqlWhere.Append($@" and a.pczt =@pczt ");
                    sqlParams.Add(new NpgsqlParameter("pczt", pageRequest.Pczt));
                }
                if (pageRequest.Yhly == 1)
                {
                    sbSqlWhere2.Append($@" and yhly='自查' ");
                }
                if (pageRequest.Yhly == 2)
                {
                    sbSqlWhere2.Append($@" and yhly='核查' ");
                }
                if (!string.IsNullOrWhiteSpace(pageRequest.Text))
                {
                    sbSqlWhere.Append($@" and (b.fwbh like @text or b.hzxm like @text or b.address like @text) ");
                    sqlParams.Add(new NpgsqlParameter("text", $"{"%" + pageRequest.Text + "%"}"));
                }
                if (pageRequest.CheckTime != null)
                {
                    if (pageRequest.CheckTime.Count == 2)
                    {
                        sbSqlWhere.Append($@" and date(create_on) between @start and @end  ");
                        sqlParams.Add(new NpgsqlParameter("start", pageRequest.CheckTime[0]));
                        sqlParams.Add(new NpgsqlParameter("end", pageRequest.CheckTime[1]));
                    }
                }
                sbSql.Append($@" select *from ( SELECT case when  jcly='2' then '市级核验' when  jcly='3' then '区级核验' when jcly='4' then '乡镇核验' end jcly  , (select nickname create_name from zm_user_cj where number=a.create_by), b.hzxm, b.address, a.id, a.fwbh, a.pczt, a.create_by, a.create_on, a.pcsj, a.jczt,'核查' yhly
        FROM zm_pc_yhlog_sqjz a
        JOIN zm_buildings b ON a.fwbh = b.fwbh where 1=1 and  base_id in (select id from zm_pc_baselog_sqjz where id=base_id  )and 1=1   {sbSqlWhere} 
         union all
        SELECT  '' jcly,(select nickname create_name from zm_user_cj where number=a.create_by),b.hzxm, b.address, a.id, a.fwbh, a.pczt, a.create_by, a.create_on, a.pcsj, a.jczt,'自查'yhly
        FROM zm_pc_yhlog a
        JOIN zm_buildings b ON a.fwbh = b.fwbh where 1=1 {sbSqlWhere}   )a  where 1=1 {sbSqlWhere2} ");

                var count = _dbContext.ZmPcYhLogAllDto.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).Count();
                sbSql.Append($@" order by create_on desc");
                sbSql.Append($@" limit @limit offset @offset");
                sqlParams.Add(new NpgsqlParameter("limit", pageRequest.Limit));

                sqlParams.Add(new NpgsqlParameter("offset", pageRequest.Limit * pageRequest.PageIndex));

                var datas = _dbContext.ZmPcYhLogAllDto.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).Select(_ => _mapper.Map<ZmPcYhLogAllDto2>(_)).ToList();


                var pageData = new Page<ZmPcYhLogAllDto2>(datas
                    , pageRequest.PageIndex + 1, pageRequest.Limit, count);

                var r = new RespRet<Page<ZmPcYhLogAllDto2>>(true, "Ok", pageData);
                WriteSystemLog("housessqjz/searchcj-attralllog", r, pageRequest);
                return r;
            }
            catch (Exception ex)
            {
                var res = new RespRet<Page<ZmPcYhLogAllDto2>>(false, ex.ToString());
                WriteSystemLogError("housessqjz/searchcj-attralllog", res, pageRequest);
                res.Msg = "系统异常";
                return res;
            }
        }

        /// <summary>
        /// 检查记录返回房屋
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("housessqjz/searchcj-attryhzcfw")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<ZmPcYhLogCjDto2>>), 200)]
        public RespRet<Page<ZmPcYhLogCjDto2>> SearchAttrList([FromBody] PageHouseRequestInputCj pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<ZmPcYhLogCjDto2>>(false, "PageIndex must >= 0");
            }
            var userNumber = this.CurrentUser();
            var user = _dbContext.ZmUser.FirstOrDefault(u => u.Number == userNumber && u.IsDelete != 1 && u.Disabled != 1);
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet<Page<ZmPcYhLogCjDto2>>(false, "user not logined");
            }
            try
            {
                var sbSql = new StringBuilder();
                var sbCountSql = new StringBuilder();
                var sbSqlWhere = new StringBuilder();
                var sbSqlWhere2 = new StringBuilder();
                var sqlParams = new List<NpgsqlParameter>();
                if (!string.IsNullOrWhiteSpace(pageRequest.Villagedm))
                {
                    sbSqlWhere.Append($@" and b.villagedm like @villagedm ");
                    sqlParams.Add(new NpgsqlParameter("villagedm", $"{"%" + pageRequest.Villagedm + "%"}"));
                }
                if (!string.IsNullOrWhiteSpace(pageRequest.Towndm))
                {
                    sbSqlWhere.Append($@" and b.Towndm like @Towndm ");
                    sqlParams.Add(new NpgsqlParameter("Towndm", $"{"%" + pageRequest.Towndm + "%"}"));
                }
                if (!string.IsNullOrWhiteSpace(pageRequest.Xzqdm))
                {
                    sbSqlWhere.Append($@" and b.Xzqdm like @Xzqdm ");
                    sqlParams.Add(new NpgsqlParameter("Xzqdm", $"{"%" + pageRequest.Xzqdm + "%"}"));
                }

                if (!string.IsNullOrWhiteSpace(pageRequest.Text))
                {
                    sbSqlWhere.Append($@" and (b.fwbh like @text or b.hzxm like @text or b.address like @text) ");
                    sqlParams.Add(new NpgsqlParameter("text", $"{"%" + pageRequest.Text + "%"}"));
                }
                //默认全部
                sbSql.Append($@" SELECT b.fwbh,b.address,b.hzxm
FROM  zm_buildings    b
full JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
full JOIN zm_pc_yh zc ON b.fwbh = zc.fwbh
WHERE 1=1  ");
                sbCountSql.Append($@" SELECT count(1) count
FROM zm_buildings b
full JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
full JOIN zm_pc_yh zc ON b.fwbh = zc.fwbh
WHERE 1=1  ");
                sqlParams.Add(new NpgsqlParameter("yhly", user.RoleType));
                if (pageRequest.Pczt > 0)
                {

                    sbSqlWhere.Append($@" and ( zc.pczt=@pczt or cj.pczt=@pczt )  ");
                    sqlParams.Add(new NpgsqlParameter("pczt", pageRequest.Pczt));
                }
                //if (pageRequest.CheckTime != null && pageRequest.CheckTime.Count == 2)
                //{

                //}
                if (pageRequest.Zczt == 1 && pageRequest.Jczt == 1)
                {
                    sbCountSql = new StringBuilder();
                    sbSql = new StringBuilder();
                    sbSql.Append($@" SELECT b.fwbh,b.address,b.hzxm
FROM zm_buildings b
right JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
 JOIN zm_pc_yh zc ON b.fwbh = zc.fwbh
WHERE 1=1 AND (cj.fwbh IS NOT NULL and zc.fwbh IS NOT NULL) ");
                    sbCountSql.Append($@" SELECT count(1) count
FROM zm_buildings b
right JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
 JOIN zm_pc_yh zc ON b.fwbh = zc.fwbh
WHERE 1=1 AND (cj.fwbh IS NOT NULL and zc.fwbh IS NOT NULL) ");
                    if (pageRequest.CheckTime != null && pageRequest.CheckTime.Count == 2)
                    {
                        sbCountSql = new StringBuilder();
                        sbSql = new StringBuilder();
                        sbSql.Append($@" SELECT b.fwbh,b.address,b.hzxm
FROM zm_buildings b
left JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
 left join zm_pc_yh zc ON b.fwbh = zc.fwbh
WHERE 1=1 and (date(zc.create_on) between date(@starttime) and date(@endtime)   and date(cj.create_on) between date(@starttime) and date(@endtime))  ");
                        sbCountSql.Append($@" SELECT count(1) count
FROM zm_buildings b
left JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
 left join zm_pc_yh zc ON b.fwbh = zc.fwbh
WHERE 1=1  and (date(zc.create_on) between date(@starttime) and date(@endtime)   and date(cj.create_on) between date(@starttime) and date(@endtime))   ");
                        sqlParams.Add(new NpgsqlParameter("starttime", pageRequest.CheckTime[0]));
                        sqlParams.Add(new NpgsqlParameter("endtime", pageRequest.CheckTime[1]));
                    }
                }
                else if (pageRequest.Zczt == 2 && pageRequest.Jczt == 2)
                {
                    sbCountSql = new StringBuilder();
                    sbSql = new StringBuilder();
                    sbSql.Append($@" SELECT b.fwbh,b.address,b.hzxm
FROM zm_buildings b
full JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
 full JOIN zm_pc_yh zc ON b.fwbh = zc.fwbh
WHERE 1=1 AND (cj.fwbh IS  NULL and zc.fwbh IS  NULL) ");
                    sbCountSql.Append($@" SELECT count(1) count
FROM zm_buildings b
full JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
full JOIN zm_pc_yh zc ON b.fwbh = zc.fwbh
WHERE 1=1 AND (cj.fwbh IS  NULL and zc.fwbh IS  NULL) ");
                    if (pageRequest.CheckTime != null && pageRequest.CheckTime.Count == 2)
                    {
                        sbCountSql = new StringBuilder();
                        sbSql = new StringBuilder();
                        sbSql.Append($@" SELECT b.fwbh,b.address,b.hzxm
FROM zm_buildings b
left JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
 left join zm_pc_yh zc ON b.fwbh = zc.fwbh
WHERE 1=1  and ((date(zc.create_on) not between date(@starttime) and date(@endtime) or zc.create_on is null )   and (date(cj.create_on) not between date(@starttime) and date(@endtime)) or cj.create_on is null )  ");
                        sbCountSql.Append($@" SELECT count(1) count
FROM zm_buildings b
left JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
 left join zm_pc_yh zc ON b.fwbh = zc.fwbh
WHERE 1=1  and ((date(zc.create_on) not between date(@starttime) and date(@endtime) or zc.create_on is null )   and (date(cj.create_on) not between date(@starttime) and date(@endtime)) or cj.create_on is null )  ");
                        sqlParams.Add(new NpgsqlParameter("starttime", pageRequest.CheckTime[0]));
                        sqlParams.Add(new NpgsqlParameter("endtime", pageRequest.CheckTime[1]));
                    }
                }
                else if (pageRequest.Zczt == 1 && pageRequest.Jczt == 2)
                {
                    sbCountSql = new StringBuilder();
                    sbSql = new StringBuilder();
                    sbSql.Append($@" SELECT b.fwbh,b.address,b.hzxm
FROM zm_buildings b
left JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
left JOIN zm_pc_yh zc ON b.fwbh = zc.fwbh
WHERE 1=1 AND (cj.fwbh IS  NULL and zc.fwbh IS NOT NULL) and b.fwbh is not null ");
                    sbCountSql.Append($@" SELECT count(1) count
FROM zm_buildings b
left JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
left JOIN zm_pc_yh zc ON b.fwbh = zc.fwbh
WHERE 1=1 AND (cj.fwbh IS  NULL and zc.fwbh IS NOT NULL) and b.fwbh is not null ");
                    if (pageRequest.CheckTime != null && pageRequest.CheckTime.Count == 2)
                    {
                        sbCountSql = new StringBuilder();
                        sbSql = new StringBuilder();
                        sbSql.Append($@" SELECT b.fwbh,b.address,b.hzxm
FROM zm_buildings b
left JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
 left join zm_pc_yh zc ON b.fwbh = zc.fwbh
WHERE 1=1  and date(zc.create_on)  between date(@starttime) and date(@endtime)   and ((date(cj.create_on) not between date(@starttime) and date(@endtime)) or cj.create_on is null )  ");
                        sbCountSql.Append($@" SELECT count(1) count
FROM zm_buildings b
left JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
 left join zm_pc_yh zc ON b.fwbh = zc.fwbh
WHERE 1=1  and date(zc.create_on)  between date(@starttime) and date(@endtime)   and ((date(cj.create_on) not between date(@starttime) and date(@endtime)) or cj.create_on is null )  ");
                        sqlParams.Add(new NpgsqlParameter("starttime", pageRequest.CheckTime[0]));
                        sqlParams.Add(new NpgsqlParameter("endtime", pageRequest.CheckTime[1]));
                    }

                }
                else if (pageRequest.Zczt == 2 && pageRequest.Jczt == 1)
                {
                    sbCountSql = new StringBuilder();
                    sbSql = new StringBuilder();
                    sbSql.Append($@" SELECT b.fwbh,b.address,b.hzxm
FROM zm_buildings b
left JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
left JOIN zm_pc_yh zc ON b.fwbh = zc.fwbh
WHERE 1=1 AND (cj.fwbh IS NOT  NULL and zc.fwbh IS  NULL) and b.fwbh is not null  ");
                    sbCountSql.Append($@" SELECT count(1) count
FROM zm_buildings b
left JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
left JOIN zm_pc_yh zc ON b.fwbh = zc.fwbh
WHERE 1=1 AND (cj.fwbh IS not NULL and zc.fwbh IS  NULL) and b.fwbh is not null ");
                    if (pageRequest.CheckTime != null && pageRequest.CheckTime.Count == 2)
                    {
                        sbCountSql = new StringBuilder();
                        sbSql = new StringBuilder();
                        sbSql.Append($@" SELECT b.fwbh,b.address,b.hzxm
FROM zm_buildings b
left JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
 left join zm_pc_yh zc ON b.fwbh = zc.fwbh
WHERE 1=1  and ((date(zc.create_on) not between date(@starttime) and date(@endtime) or zc.create_on is null )   and date(cj.create_on)  between date(@starttime) and date(@endtime))  ");
                        sbCountSql.Append($@" SELECT count(1) count
FROM zm_buildings b
left JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
 left join zm_pc_yh zc ON b.fwbh = zc.fwbh
WHERE 1=1  and ((date(zc.create_on) not between date(@starttime) and date(@endtime) or zc.create_on is null )   and date(cj.create_on)  between date(@starttime) and date(@endtime))  ");
                        sqlParams.Add(new NpgsqlParameter("starttime", pageRequest.CheckTime[0]));
                        sqlParams.Add(new NpgsqlParameter("endtime", pageRequest.CheckTime[1]));
                    }
                }
                else if (pageRequest.Zczt == 1)
                {
                    sbCountSql = new StringBuilder();
                    sbSql = new StringBuilder();
                    sbSql.Append($@" SELECT b.fwbh,b.address,b.hzxm
FROM zm_buildings b
left JOIN zm_pc_yh zc ON b.fwbh = zc.fwbh
left  JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
WHERE 1=1 and zc.fwbh is not null   ");
                    sbCountSql.Append($@" SELECT count(1) count
FROM zm_buildings b
left JOIN zm_pc_yh zc ON b.fwbh = zc.fwbh
left  JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
WHERE 1=1 and zc.fwbh is not null  ");
                    if (pageRequest.CheckTime != null && pageRequest.CheckTime.Count == 2)
                    {
                        sbCountSql = new StringBuilder();
                        sbSql = new StringBuilder();
                        sbSql.Append($@" SELECT b.fwbh,b.address,b.hzxm
FROM zm_buildings b
left JOIN zm_pc_yh zc ON b.fwbh = zc.fwbh
left  JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
WHERE 1=1    and date(zc.create_on)  between date(@starttime) and date(@endtime)  ");
                        sbCountSql.Append($@" SELECT count(1) count
FROM zm_buildings b
left JOIN zm_pc_yh zc ON b.fwbh = zc.fwbh
left  JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
WHERE 1=1    and date(zc.create_on)  between date(@starttime) and date(@endtime)  ");
                        sqlParams.Add(new NpgsqlParameter("starttime", pageRequest.CheckTime[0]));
                        sqlParams.Add(new NpgsqlParameter("endtime", pageRequest.CheckTime[1]));
                    }
                }
                else if (pageRequest.Zczt == 2)
                {
                    sbCountSql = new StringBuilder();
                    sbSql = new StringBuilder();
                    sbSql.Append($@" SELECT b.fwbh,b.address,b.hzxm
FROM zm_buildings b
left  JOIN zm_pc_yh zc ON b.fwbh = zc.fwbh
left JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
WHERE 1=1 and zc.fwbh is null ");
                    sbCountSql.Append($@" SELECT count(1) count
FROM zm_buildings b
left  JOIN zm_pc_yh zc ON b.fwbh = zc.fwbh
left JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
WHERE 1=1  and zc.fwbh is null ");
                    if (pageRequest.CheckTime != null && pageRequest.CheckTime.Count == 2)
                    {
                        sbCountSql = new StringBuilder();
                        sbSql = new StringBuilder();
                        sbSql.Append($@" SELECT b.fwbh,b.address,b.hzxm
FROM zm_buildings b
left  JOIN zm_pc_yh zc ON b.fwbh = zc.fwbh
left JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
WHERE 1=1  and (date(zc.create_on) not between date(@starttime) and date(@endtime) or zc.create_on is null )  ");
                        sbCountSql.Append($@" SELECT count(1) count
FROM zm_buildings b
left  JOIN zm_pc_yh zc ON b.fwbh = zc.fwbh
left JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
WHERE 1=1   and ( date(zc.create_on) not between date(@starttime) and date(@endtime) or zc.create_on is null ) ");
                        sqlParams.Add(new NpgsqlParameter("starttime", pageRequest.CheckTime[0]));
                        sqlParams.Add(new NpgsqlParameter("endtime", pageRequest.CheckTime[1]));
                    }
                }
                else if (pageRequest.Jczt == 2)
                {
                    sbCountSql = new StringBuilder();
                    sbSql = new StringBuilder();
                    sbSql.Append($@" SELECT b.fwbh,b.address,b.hzxm
FROM zm_buildings b
left  JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
left JOIN zm_pc_yh zc ON b.fwbh = zc.fwbh
WHERE 1=1 and cj.fwbh is null  ");
                    sbCountSql.Append($@" SELECT count(1) count
FROM zm_buildings b
left JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
left JOIN zm_pc_yh zc ON b.fwbh = zc.fwbh
WHERE 1=1 and cj.fwbh is null  ");
                    if (pageRequest.CheckTime != null && pageRequest.CheckTime.Count == 2)
                    {
                        sbCountSql = new StringBuilder();
                        sbSql = new StringBuilder();
                        sbSql.Append($@" SELECT b.fwbh,b.address,b.hzxm
FROM zm_buildings b
left  JOIN zm_pc_yh zc ON b.fwbh = zc.fwbh
left JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
WHERE 1=1  and (date(cj.create_on) not between date(@starttime) and date(@endtime) or cj.create_on is null ) ");
                        sbCountSql.Append($@" SELECT count(1) count
FROM zm_buildings b
left  JOIN zm_pc_yh zc ON b.fwbh = zc.fwbh
left JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
WHERE 1=1   and (date(cj.create_on) not between date(@starttime) and date(@endtime) or cj.create_on is null )  ");
                        sqlParams.Add(new NpgsqlParameter("starttime", pageRequest.CheckTime[0]));
                        sqlParams.Add(new NpgsqlParameter("endtime", pageRequest.CheckTime[1]));
                    }
                }
                else if (pageRequest.Jczt == 1)
                {
                    sbCountSql = new StringBuilder();
                    sbSql = new StringBuilder();
                    sbSql.Append($@" SELECT b.fwbh,b.address,b.hzxm
FROM zm_buildings b
left JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
left JOIN zm_pc_yh zc ON b.fwbh = zc.fwbh
WHERE 1=1 and cj.fwbh is not  null ");
                    sbCountSql.Append($@" SELECT count(1) count
FROM zm_buildings b
left JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
left JOIN zm_pc_yh zc ON b.fwbh = zc.fwbh
WHERE 1=1 and cj.fwbh is not null ");
                    if (pageRequest.CheckTime != null && pageRequest.CheckTime.Count == 2)
                    {
                        sbCountSql = new StringBuilder();
                        sbSql = new StringBuilder();
                        sbSql.Append($@" SELECT b.fwbh,b.address,b.hzxm
FROM zm_buildings b
left  JOIN zm_pc_yh zc ON b.fwbh = zc.fwbh
left JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
WHERE 1=1  and date(cj.create_on)  between date(@starttime) and date(@endtime)   ");
                        sbCountSql.Append($@" SELECT count(1) count
FROM zm_buildings b
left  JOIN zm_pc_yh zc ON b.fwbh = zc.fwbh
left JOIN (select * from  zm_pc_yh_sqjz where yhly=@yhly) cj ON b.fwbh = cj.fwbh
WHERE 1=1   and date(cj.create_on)  between date(@starttime) and date(@endtime) ");
                        sqlParams.Add(new NpgsqlParameter("starttime", pageRequest.CheckTime[0]));
                        sqlParams.Add(new NpgsqlParameter("endtime", pageRequest.CheckTime[1]));
                    }
                }

                sbCountSql.Append(sbSqlWhere);
                sbSql.Append(sbSqlWhere);
                var count = _dbContext.CountClass.FromSqlRaw(sbCountSql.ToString(), sqlParams.ToArray()).FirstOrDefault();
                sbSql.Append($@" order by fwbh ");
                sbSql.Append($@" limit @limit offset @offset");
                sqlParams.Add(new NpgsqlParameter("limit", pageRequest.Limit));
                sqlParams.Add(new NpgsqlParameter("offset", pageRequest.Limit * pageRequest.PageIndex));

                var datas = _dbContext.ZmPcYhLogCjDto.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).ToList();
                var data = datas.Select(_ => _mapper.Map<ZmPcYhLogCjDto2>(_)).ToList();
                var pageData = new Page<ZmPcYhLogCjDto2>(data
                    , pageRequest.PageIndex + 1, pageRequest.Limit, count.Count);
                var r = new RespRet<Page<ZmPcYhLogCjDto2>>(true, "Ok", pageData);
                WriteSystemLog("housessqjz/search-attryhzclog", r, pageRequest);
                return r;
            }
            catch (Exception ex)
            {
                var res = new RespRet<Page<ZmPcYhLogCjDto2>>(false, ex.ToString());
                WriteSystemLogError("housessqjz/search-attryhzclog", res, pageRequest);
                res.Msg = "系统异常";
                return res;
            }
        }


        /// <summary>
        /// 房屋列表
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("housessqjz/search-fwlb")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<FwlbDto>>), 200)]
        public RespRet<PagePc<object>> Fwlb([FromBody] Fwlb pageRequest)
        {
            if (pageRequest == null)
            {
                return new RespRet<PagePc<object>>(false, "请传递参数");
            }
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<PagePc<object>>(false, "PageIndex must >= 0");
            }
            var userNumber = this.CurrentUser();
            var user = _dbContext.ZmUser.FirstOrDefault(c => c.Number == userNumber && c.IsDelete != 1 && c.Disabled != 1);
            var a = JsonRegion(user.District);
            JObject obj = JObject.Parse(user.District);
            string RegionCode = (string)obj["RegionCode"];
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet<PagePc<object>>(false, "user not logined");
            }
            try
            {




                var sqlParams = new List<NpgsqlParameter>();
                string city_sql = "select b.yhly,a.pczt, b.create_name,a.fwbh,b.fwzt,a.create_on from  zm_pc_yh_sqjz a,zm_pc_base_sqjz b where a.base_id=b.id and b.yhly='2' ";
                string xzq_sql = "select b.yhly,a.pczt, b.create_name,a.fwbh,b.fwzt,a.create_on  from  zm_pc_yh_sqjz a,zm_pc_base_sqjz b where a.base_id=b.id and b.yhly='3'";
                string town_sql = "select b.yhly,a.pczt, b.create_name,a.fwbh,b.fwzt,a.create_on  from  zm_pc_yh_sqjz a,zm_pc_base_sqjz b where a.base_id=b.id and b.yhly='4'";

                DateTime startime = DateTime.Now;
                DateTime endtime = DateTime.Now;
                if (pageRequest.date != null && pageRequest.date.Count == 2)
                {
                    startime = pageRequest.date[0];
                    endtime = pageRequest.date[1];
                    endtime = endtime.AddHours(23);
                    endtime = endtime.AddMinutes(59);
                    endtime = endtime.AddSeconds(59);
                    sqlParams.Add(new NpgsqlParameter("startime", startime));
                    sqlParams.Add(new NpgsqlParameter("endtime", endtime));
                }
                string time = DateTime.Today
                    .AddHours(23)
                    .AddMinutes(59)
                    .AddSeconds(59)
                    .ToString("yyyy-MM-dd HH:mm:ss");
                sqlParams.Add(new NpgsqlParameter("time", time));

                string table_name = "zm_building_fwzt_" + DateTime.Now.Year;


                var sbSql = new StringBuilder();
                var sbSqlCount = new StringBuilder();
                var yccbczsql = new StringBuilder();
                var sbSqlWhere = new StringBuilder();

                string fwzt_where = "";

                if (pageRequest.fwzt != 0)
                {
                    fwzt_where = $" select * from zm_buildings t1 where fwbh  in  (select fwbh From  {table_name} where final_create_on=@time  and final_fwzt=@fwzt  ) ";
                    sqlParams.Add(new NpgsqlParameter("fwzt", pageRequest.fwzt));

                }
                else
                {
                    fwzt_where = $" select * from zm_buildings t1 where fwbh  not in  (select fwbh From  {table_name} where final_create_on=@time  and final_fwzt is not null  )  ";
                }

                string count_yhly = "";
                if (pageRequest.yhly > 0)
                {
                    count_yhly = " and b.yhly=@yhly ";
                }





                sbSql.Append($@" SELECT
 case when @fwzt=0 then null else @fwzt  end fwzt,
 max(case when  cjbase.fwzt is null then 0 else cjbase.fwzt end) fwztjc,
 max(case when  aaa.fwzt is null then 0 else aaa.fwzt end ) fwztjzhc,
 max(case when  aa.fwzt is null then 0 else aa.fwzt end  ) fwztqjhc,
 max(case when  a.fwzt is null then 0 else a.fwzt end  ) fwztsjhc,
 b.fwbh as id,
 TO_CHAR(max(a.create_on), 'YYYY-MM-DD HH24:MI:SS') sjhcsj,
 TO_CHAR(max(aa.create_on), 'YYYY-MM-DD HH24:MI:SS') qjhcsj,
 TO_CHAR(max(aaa.create_on), 'YYYY-MM-DD HH24:MI:SS') jzhcsj,
 TO_CHAR(max(cj.create_on), 'YYYY-MM-DD HH24:MI:SS') jcsj,
 TO_CHAR(max(d.create_on), 'YYYY-MM-DD HH24:MI:SS') zcsj,
 max(b.address) address, 
 max(b.hzxm) hzxm, 
 b.fwbh, 
 ST_X(ST_Centroid(ST_Collect(geom))) AS villagelongitude,
 ST_Y(ST_Centroid(ST_Collect(geom))) AS villagelatitude,
 max(st_asgeojson(geom)) AS geometry,
 CASE
        WHEN max(geom) IS NULL THEN NULL
        ELSE json_build_object(
            'type', 'Feature',
            'geometry', json_build_object(
                'type', 'MultiPolygon',
                'coordinates', ST_AsGeoJSON(max(geom))::json->'coordinates'
            ),
            'properties', json_build_object(
                'fwbh', max(b.fwbh),
                'address',max(b.address), 
                'hzxm',max(b.hzxm)
            )
        )
    END AS feature,
  max(case when  a.pczt is null then 0 else a.pczt end ) sjpczt,
	max(case when  aa.pczt is null then 0 else aa.pczt end ) qjpczt,
	max(case when  aaa.pczt is null then 0 else aaa.pczt end ) jzpczt,
	max(case when  d.pczt is null then 0 else d.pczt end )zczt,
	max(case when  cj.pczt is null then 0 else cj.pczt end )jczt,
	max(a.create_name) sjhcr,
	max(aa.create_name) qjhcr,
	max(aaa.create_name) jzhcr,
	max(cjbase.create_name) jcr,
 max(case when	DATE_PART('day', now() -d.create_on)::text is null then '' else DATE_PART('day', now() -d.create_on)::text end )AS day_difference			
FROM 
     ( {fwzt_where}  )  b   
LEFT JOIN   ({city_sql})   a ON b.fwbh = a.fwbh
LEFT JOIN   ({xzq_sql})   aa ON b.fwbh = aa.fwbh
LEFT JOIN 	({town_sql} )   aaa ON b.fwbh = aaa.fwbh
LEFT JOIN  zm_pc_yh  d ON d.fwbh = b.fwbh left join zm_pc_yh_cj cj on b.fwbh=cj.fwbh
left join zm_pc_base zcbase on b.fwbh=zcbase.fwbh
left join zm_pc_base_cj cjbase on b.fwbh=cjbase.fwbh 
where 1=1  ");

                sbSqlCount.Append($@" SELECT
 count(distinct b.fwbh) count	,
  1 yjc,2 wjc,1 yzc,2 wzc
FROM 
     ( {fwzt_where} )  b     
LEFT JOIN 
       (select a.* from  zm_pc_yh_sqjz a,zm_pc_base_sqjz b where a.base_id=b.id {count_yhly}  )   a ON b.fwbh = a.fwbh
LEFT JOIN  zm_pc_yh  d ON d.fwbh = b.fwbh 
left join zm_pc_base zcbase on b.fwbh=zcbase.fwbh 
left join zm_pc_base_cj cjbase on b.fwbh=cjbase.fwbh 
where 1=1  ");
                yccbczsql.Append($@" SELECT
 count(1) count	,
1 yjc,2 wjc,1 yzc,2 wzc
FROM 
    ({fwzt_where} )  b    
LEFT JOIN 
      (select a.* from  zm_pc_yh_sqjz a,zm_pc_base_sqjz b where a.base_id=b.id   )   a ON b.fwbh = a.fwbh
LEFT JOIN  zm_pc_yh  d ON d.fwbh = b.fwbh 
left join zm_pc_base zcbase on b.fwbh=zcbase.fwbh 
left join zm_pc_base_cj cjbase on b.fwbh=cjbase.fwbh 
where 1=1  ");

                var CountSql = new StringBuilder();
                CountSql.Append($@"  SELECT
 count(case when d.pczt is null then 1 end) wzc,
 count(case when d.pczt is not null then 1 end) yzc,
 count(case when a.fwbh is null then 1 end) wjc,
 count(case when a.fwbh is not null then 1 end) yjc,
1 count 
FROM 
    ({fwzt_where} )  b   
LEFT JOIN 
   (select a.* from  zm_pc_yh_sqjz a,zm_pc_base_sqjz b where a.base_id=b.id and b.yhly=@yhly  )  a  ON b.fwbh = a.fwbh 
LEFT JOIN 
  zm_pc_yh  d ON d.fwbh = b.fwbh 
left join zm_pc_base zcbase on b.fwbh=zcbase.fwbh 
left join zm_pc_base_cj cjbase on b.fwbh=cjbase.fwbh 
where 1=1  ");
                //2024-11-20，将村级或自查三层的改为只查自查三层的
                if (pageRequest.cs == 1 || pageRequest.cs == 2)
                {
                    //CountSql.Append($@" and (zcbase.cs=@cs or cjbase.cs=@cs )");
                    //sbSql.Append($@" and (zcbase.cs=@cs or cjbase.cs=@cs ) ");
                    //sbSqlCount.Append($@" and (zcbase.cs=@cs or cjbase.cs=@cs ) ");
                    //yccbczsql.Append($@" and (zcbase.cs=@cs or cjbase.cs=@cs ) ");
                    //sqlParams.Add(new NpgsqlParameter("cs", pageRequest.cs));
                    CountSql.Append($@" and (zcbase.cs=@cs  )");
                    sbSql.Append($@" and (zcbase.cs=@cs  ) ");
                    sbSqlCount.Append($@" and (zcbase.cs=@cs  ) ");
                    yccbczsql.Append($@" and (zcbase.cs=@cs  ) ");
                    sqlParams.Add(new NpgsqlParameter("cs", pageRequest.cs));
                }

                else if (pageRequest.cs == 3)
                {
                    //CountSql.Append($@"and (zcbase.cs>2 or cjbase.cs>2 ) ");
                    //sbSql.Append($@" and (zcbase.cs>2 or cjbase.cs>2 )");
                    //sbSqlCount.Append($@" and (zcbase.cs>2 or cjbase.cs>2 ) ");
                    //yccbczsql.Append($@" and (zcbase.cs>2 or cjbase.cs>2 ) ");
                    CountSql.Append($@"and (zcbase.cs>2  ) ");
                    sbSql.Append($@" and (zcbase.cs>2 )");
                    sbSqlCount.Append($@" and (zcbase.cs>2 ) ");
                    yccbczsql.Append($@" and (zcbase.cs>2) ");
                }
                //自查或村级检查达标
                if (pageRequest.isdb == 1)
                {
                    CountSql.Append($@" and (((zcbase.Cs <= 1 and zcbase.Jzscxyaqcksl >= 2) or (zcbase.Cs >= 2 and zcbase.Jzscxyaqcksl >= 2 and zcbase.Jzxyssltsl >= 2)) or cjbase.jsrysstd='是')  ");
                    sbSql.Append($@" and (((zcbase.Cs <= 1 and zcbase.Jzscxyaqcksl >= 2) or (zcbase.Cs >= 2 and zcbase.Jzscxyaqcksl >= 2 and zcbase.Jzxyssltsl >= 2)) or cjbase.jsrysstd='是')  ");
                    sbSqlCount.Append($@" and (((zcbase.Cs <= 1 and zcbase.Jzscxyaqcksl >= 2) or (zcbase.Cs >= 2 and zcbase.Jzscxyaqcksl >= 2 and zcbase.Jzxyssltsl >= 2)) or cjbase.jsrysstd='是' ) ");
                    yccbczsql.Append($@" and (((zcbase.Cs <= 1 and zcbase.Jzscxyaqcksl >= 2) or (zcbase.Cs >= 2 and zcbase.Jzscxyaqcksl >= 2 and zcbase.Jzxyssltsl >= 2)) or cjbase.jsrysstd='是' ) ");
                }
                else if (pageRequest.isdb == 0)
                {
                    CountSql.Append($@" and (((zcbase.Cs <= 1 and zcbase.Jzscxyaqcksl < 2) or (zcbase.Cs >= 2 and (zcbase.Jzscxyaqcksl < 2 or zcbase.Jzxyssltsl < 2))) or cjbase.jsrysstd='否')  ");
                    sbSql.Append($@" and (((zcbase.Cs <= 1 and zcbase.Jzscxyaqcksl < 2) or (zcbase.Cs >= 2 and (zcbase.Jzscxyaqcksl < 2 or zcbase.Jzxyssltsl < 2))) or cjbase.jsrysstd='否')  ");
                    sbSqlCount.Append($@" and (((zcbase.Cs <= 1 and zcbase.Jzscxyaqcksl < 2) or (zcbase.Cs >= 2 and (zcbase.Jzscxyaqcksl < 2 or zcbase.Jzxyssltsl < 2))) or cjbase.jsrysstd='否' ) ");
                    yccbczsql.Append($@" and (((zcbase.Cs <= 1 and zcbase.Jzscxyaqcksl < 2) or (zcbase.Cs >= 2 and (zcbase.Jzscxyaqcksl < 2 or zcbase.Jzxyssltsl < 2))) or cjbase.jsrysstd='否')  ");
                }


                if (!string.IsNullOrWhiteSpace(pageRequest.Villagedm))
                {
                    CountSql.Append($@" and b.villagedm=@villagedm ");
                    sbSql.Append($@" and b.villagedm=@villagedm ");
                    sbSqlCount.Append($@" and b.villagedm=@villagedm ");
                    yccbczsql.Append($@" and b.villagedm=@villagedm ");
                    sqlParams.Add(new NpgsqlParameter("villagedm", $"{pageRequest.Villagedm}"));
                }
                if (!string.IsNullOrWhiteSpace(pageRequest.Towndm))
                {
                    CountSql.Append($@" and b.towndm=@towndm ");
                    sbSql.Append($@" and b.towndm=@towndm ");
                    sbSqlCount.Append($@" and b.towndm=@towndm ");
                    yccbczsql.Append($@" and b.towndm=@towndm ");
                    sqlParams.Add(new NpgsqlParameter("towndm", $"{pageRequest.Towndm}"));
                }
                if (!string.IsNullOrWhiteSpace(pageRequest.Xzqdm))
                {
                    CountSql.Append($@" and b.xzqdm=@xzqdm ");
                    sbSql.Append($@" and b.xzqdm=@xzqdm ");
                    sbSqlCount.Append($@" and b.xzqdm=@xzqdm ");
                    yccbczsql.Append($@" and b.xzqdm=@xzqdm ");
                    sqlParams.Add(new NpgsqlParameter("xzqdm", $"{pageRequest.Xzqdm}"));
                }
                if (pageRequest.pczt != null)
                {
                    if (pageRequest.pczt == 0)
                    {
                        CountSql.Append($@" and a.pczt is null ");
                        sbSql.Append($@" and a.pczt is null ");
                        yccbczsql.Append($@" and a.pczt is null ");
                        sbSqlCount.Append($@" and a.pczt is null ");
                    }
                    else
                    {
                        CountSql.Append($@" and a.pczt=@pczt ");
                        sbSql.Append($@" and a.pczt=@pczt ");
                        sbSqlCount.Append($@" and a.pczt=@pczt ");
                        yccbczsql.Append($@" and a.pczt=@pczt ");
                        sqlParams.Add(new NpgsqlParameter("pczt", pageRequest.pczt));
                    }
                }




                if (pageRequest.ispc != null)
                {
                    if (pageRequest.yhly == 2)
                    {
                        if (pageRequest.ispc == 0)
                        {

                            if (pageRequest.date != null && pageRequest.date.Count == 2)
                            {
                                CountSql.Append($@" and (a.create_on not between @startime and @endtime or a.create_on is null  ) ");
                                sbSql.Append($@" and (a.create_on not between @startime and @endtime or a.create_on is null  )  ");
                                yccbczsql.Append($@" and (a.create_on not between @startime and @endtime or a.create_on is null  ) ");
                                sbSqlCount.Append($@" and (a.create_on not between @startime and @endtime or a.create_on is null  ) ");
                            }
                            else
                            {
                                CountSql.Append($@" and a.pczt is null ");
                                sbSql.Append($@" and a.pczt is null ");
                                yccbczsql.Append($@" and a.pczt is null ");
                                sbSqlCount.Append($@" and a.pczt is null ");
                            }
                        }
                        else
                        {

                            if (pageRequest.date != null && pageRequest.date.Count == 2)
                            {
                                CountSql.Append($@" and a.create_on  between @startime and @endtime ");
                                sbSql.Append($@" and  a.create_on  between @startime and @endtime ");
                                yccbczsql.Append($@" and a.create_on  between @startime and @endtime ");
                                sbSqlCount.Append($@" and  a.create_on  between @startime and @endtime ");
                            }
                            else
                            {
                                CountSql.Append($@" and a.pczt is not null ");
                                sbSql.Append($@" and a.pczt is not null ");
                                sbSqlCount.Append($@" and a.pczt is not null ");
                                yccbczsql.Append($@" and a.pczt is not null ");
                                sqlParams.Add(new NpgsqlParameter("pczt", pageRequest.ispc));
                            }
                        }
                    }
                    else if (pageRequest.yhly == 3)
                    {
                        if (pageRequest.ispc == 0)
                        {
                            if (pageRequest.date != null && pageRequest.date.Count == 2)
                            {
                                CountSql.Append($@" and (a.create_on not between @startime and @endtime or a.create_on is null  ) ");
                                sbSql.Append($@" and (aa.create_on not between @startime and @endtime or aa.create_on is null  )  ");
                                yccbczsql.Append($@" and (a.create_on not between @startime and @endtime or a.create_on is null  ) ");
                                sbSqlCount.Append($@" and (a.create_on not between @startime and @endtime or a.create_on is null  ) ");
                            }
                            else
                            {
                                CountSql.Append($@" and a.pczt is null ");
                                sbSql.Append($@" and aa.pczt is null ");
                                yccbczsql.Append($@" and a.pczt is null ");
                                sbSqlCount.Append($@" and a.pczt is null ");
                            }


                        }
                        else
                        {
                            if (pageRequest.date != null && pageRequest.date.Count == 2)
                            {
                                CountSql.Append($@" and a.create_on  between @startime and @endtime ");
                                sbSql.Append($@" and  aa.create_on  between @startime and @endtime ");
                                yccbczsql.Append($@" and a.create_on  between @startime and @endtime ");
                                sbSqlCount.Append($@" and  a.create_on  between @startime and @endtime ");
                            }
                            else
                            {
                                CountSql.Append($@" and a.pczt is not null ");
                                sbSql.Append($@" and aa.pczt is not null ");
                                sbSqlCount.Append($@" and a.pczt is not null ");
                                yccbczsql.Append($@" and a.pczt is not null ");
                                sqlParams.Add(new NpgsqlParameter("pczt", pageRequest.ispc));
                            }
                        }

                    }

                    else if (pageRequest.yhly == 4)
                    {
                        if (pageRequest.ispc == 0)
                        {
                            if (pageRequest.date != null && pageRequest.date.Count == 2)
                            {
                                CountSql.Append($@" and (a.create_on not between @startime and @endtime or a.create_on is null  ) ");
                                sbSql.Append($@" and (aaa.create_on not between @startime and @endtime or aaa.create_on is null  )  ");
                                yccbczsql.Append($@" and (a.create_on not between @startime and @endtime or a.create_on is null  ) ");
                                sbSqlCount.Append($@" and (a.create_on not between @startime and @endtime or a.create_on is null  ) ");
                            }
                            else
                            {
                                CountSql.Append($@" and a.pczt is null ");
                                sbSql.Append($@" and aaa.pczt is null ");
                                yccbczsql.Append($@" and a.pczt is null ");
                                sbSqlCount.Append($@" and a.pczt is null ");
                            }
                        }
                        else
                        {
                            if (pageRequest.date != null && pageRequest.date.Count == 2)
                            {
                                CountSql.Append($@" and a.create_on  between @startime and @endtime ");
                                sbSql.Append($@" and  aaa.create_on  between @startime and @endtime ");
                                yccbczsql.Append($@" and a.create_on  between @startime and @endtime ");
                                sbSqlCount.Append($@" and  a.create_on  between @startime and @endtime ");
                            }
                            else
                            {
                                CountSql.Append($@" and a.pczt is not null ");
                                sbSql.Append($@" and aaa.pczt is not null ");
                                sbSqlCount.Append($@" and a.pczt is not null ");
                                yccbczsql.Append($@" and a.pczt is not null ");
                                sqlParams.Add(new NpgsqlParameter("pczt", pageRequest.ispc));
                            }
                        }

                    }
                    else
                    {
                        if (pageRequest.ispc == 0)
                        {
                            if (pageRequest.date != null && pageRequest.date.Count == 2)
                            {
                                CountSql.Append($@" and (a.create_on not between @startime and @endtime or a.create_on is null  ) ");
                                sbSql.Append($@" and (aaa.create_on not between @startime and @endtime or aaa.create_on is null  ) and (a.create_on not between @startime and @endtime or a.create_on is null  )  and (aa.create_on not between @startime and @endtime or aa.create_on is null  ) ");
                                yccbczsql.Append($@" and (a.create_on not between @startime and @endtime or a.create_on is null  ) ");
                                sbSqlCount.Append($@" and (a.create_on not between @startime and @endtime or a.create_on is null  ) ");
                            }
                            else
                            {
                                CountSql.Append($@" and a.pczt is null ");
                                sbSql.Append($@" and aaa.pczt is null and aa.pczt is null and a.pczt is null ");
                                yccbczsql.Append($@" and a.pczt is null ");
                                sbSqlCount.Append($@" and a.pczt is null ");
                            }
                        }
                        else
                        {
                            if (pageRequest.date != null && pageRequest.date.Count == 2)
                            {
                                CountSql.Append($@" and a.create_on  between @startime and @endtime ");
                                sbSql.Append($@" and  aaa.create_on  between @startime and @endtime and  aa.create_on  between @startime and @endtime  and  a.create_on  between @startime and @endtime ");
                                yccbczsql.Append($@" and a.create_on  between @startime and @endtime ");
                                sbSqlCount.Append($@" and  a.create_on  between @startime and @endtime ");
                            }
                            else
                            {
                                CountSql.Append($@" and a.pczt is not null ");
                                sbSql.Append($@" and aaa.pczt is not null and aa.pczt is not null and a.pczt is not null ");
                                sbSqlCount.Append($@" and a.pczt is not null ");
                                yccbczsql.Append($@" and a.pczt is not null ");
                                sqlParams.Add(new NpgsqlParameter("pczt", pageRequest.ispc));
                            }
                        }
                    }
                }

                if (!string.IsNullOrWhiteSpace(pageRequest.text))
                {
                    CountSql.Append($@" and ( b.hzxm like @text or b.address like @text or b.fwbh like @text ) ");
                    sbSql.Append($@" and ( b.hzxm like @text or b.address like @text or b.fwbh like @text ) ");
                    sbSqlCount.Append($@" and ( b.hzxm like @text or b.address like @text or b.fwbh like @text ) ");
                    yccbczsql.Append($@" and ( b.hzxm like @text or b.address like @text or b.fwbh like @text ) ");
                    sqlParams.Add(new NpgsqlParameter("text", "%" + pageRequest.text + "%"));
                }

                if (!string.IsNullOrWhiteSpace(pageRequest.fwbh))
                {
                    CountSql.Append($@" and ( b.fwbh like @fwbh ) ");
                    sbSql.Append($@" and (  b.fwbh like @fwbh ) ");
                    sbSqlCount.Append($@" and (  b.fwbh like @fwbh ) ");
                    yccbczsql.Append($@" and (  b.fwbh like @fwbh ) ");
                    sqlParams.Add(new NpgsqlParameter("fwbh", "%" + pageRequest.fwbh + "%"));
                }



                if (!string.IsNullOrWhiteSpace(pageRequest.hzxm))
                {
                    CountSql.Append($@" and ( b.hzxm like @hzxm ) ");
                    sbSql.Append($@" and (  b.hzxm like @hzxm ) ");
                    sbSqlCount.Append($@" and (  b.hzxm like @hzxm ) ");
                    yccbczsql.Append($@" and (  b.hzxm like @hzxm ) ");
                    sqlParams.Add(new NpgsqlParameter("hzxm", "%" + pageRequest.hzxm + "%"));
                }


                if (pageRequest.yhly > 0)
                {
                    if (pageRequest.ispc != null)
                    {
                        if (pageRequest.ispc == 0)
                        {
                            if (pageRequest.date != null && pageRequest.date.Count == 2)
                            {
                                if (pageRequest.yhly == 2)
                                {
                                    sbSql.Append($@" and ( a.yhly is null or a.yhly=2)  ");
                                    sbSqlCount.Append($@" and (a.jcly is null or a.jcly=2)   ");
                                }
                                if (pageRequest.yhly == 3)
                                {
                                    sbSql.Append($@" and ( a.yhly is null or a.yhly=3)  ");
                                    sbSqlCount.Append($@" and (a.jcly is null or a.jcly=3)   ");
                                }
                                if (pageRequest.yhly == 4)
                                {
                                    sbSql.Append($@" and ( a.yhly is null or a.yhly=4)  ");
                                    sbSqlCount.Append($@" and (a.jcly is null or a.jcly=4)   ");
                                }
                            }
                            else
                            {
                                if (pageRequest.yhly == 2)
                                {
                                    sbSql.Append($@" and (a.yhly is null or a.yhly!=2  ) ");
                                    sbSqlCount.Append($@" and ( a.jcly is null or a.jcly!=2 )  ");
                                }
                                if (pageRequest.yhly == 3)
                                {
                                    sbSql.Append($@" and (a.yhly is null or a.yhly!=3  ) ");
                                    sbSqlCount.Append($@" and ( a.jcly is null or a.jcly!=3 )  ");
                                }
                                if (pageRequest.yhly == 4)
                                {
                                    sbSql.Append($@" and (a.yhly is null or a.yhly!=4  ) ");
                                    sbSqlCount.Append($@" and ( a.jcly is null or a.jcly!=4 )  ");
                                }
                            }

                        }
                        else
                        {
                            if (pageRequest.yhly == 2)
                            {
                                sbSql.Append($@" and a.yhly=2  ");
                                sbSqlCount.Append($@" and a.jcly=2   ");
                            }
                            if (pageRequest.yhly == 3)
                            {
                                sbSql.Append($@" and aa.yhly=3   ");
                                sbSqlCount.Append($@" and a.jcly=3    ");
                            }
                            if (pageRequest.yhly == 4)
                            {
                                sbSql.Append($@" and aaa.yhly=4   ");
                                sbSqlCount.Append($@" and a.jcly=4   ");
                            }
                        }
                    }

                    sqlParams.Add(new NpgsqlParameter("yhly", pageRequest.yhly));
                }
                else
                {
                    sqlParams.Add(new NpgsqlParameter("yhly", pageRequest.yhly));
                }

                if (!string.IsNullOrWhiteSpace(pageRequest.address))
                {
                    CountSql.Append($@" and ( b.address like @address ) ");
                    sbSql.Append($@" and (  b.address like @address ) ");
                    sbSqlCount.Append($@" and (  b.address like @address ) ");
                    yccbczsql.Append($@" and (  b.address like @address ) ");
                    sqlParams.Add(new NpgsqlParameter("address", "%" + pageRequest.address + "%"));
                }
                sbSql.Append($@" group by b.fwbh ");
                var count = _dbContext.FwlbCount.FromSqlRaw(sbSqlCount.ToString(), sqlParams.ToArray()).FirstOrDefault();
                //var yccbcz = _dbContext.FwlbCount.FromSqlRaw(yccbczsql.ToString(), sqlParams.ToArray()).FirstOrDefault();
                //var countpc = _dbContext.FwlbCount.FromSqlRaw(CountSql.ToString(), sqlParams.ToArray()).FirstOrDefault();

                //根据不同角色  进行不同排序
                if (user.RoleType == 2)
                {
                    sbSql.Append($@" order by max(d.create_on) desc NULLS LAST,max(a.create_on) desc NULLS LAST,b.fwbh ");

                }
                else if (user.RoleType == 3)
                {
                    sbSql.Append($@" order by max(aa.create_on),max(case when DATE_PART('day', now() -d.create_on)::text is null then null else DATE_PART('day', now() -d.create_on) end )desc,b.fwbh "
                      );
                }
                else if (user.RoleType == 4)
                {
                    sbSql.Append($@" order by max(aaa.create_on),max(case when DATE_PART('day', now() -d.create_on)::text is null then null else DATE_PART('day', now() -d.create_on) end )desc,b.fwbh "
                      );
                }
                sbSql.Append($@" limit @limit offset @offset");
                sqlParams.Add(new NpgsqlParameter("limit", pageRequest.Limit));
                sqlParams.Add(new NpgsqlParameter("offset", pageRequest.Limit * pageRequest.PageIndex));
                var datas = _dbContext.Database.GetDbConnection().Query<object>(sbSql.ToString(), new { @time = time, @startime = startime, @endtime = endtime, @xzqdm = pageRequest.Xzqdm, @villagedm = pageRequest.Villagedm, @towndm = pageRequest.Towndm, @text = "%" + pageRequest.text + "%", @ispc = pageRequest.ispc, @isdb = pageRequest.isdb, @cs = pageRequest.cs, @fwbh = pageRequest.fwbh, @hzxm = pageRequest.hzxm, @fwzt = pageRequest.fwzt, @address = pageRequest.address, @yhly = user.RoleType, @limit = pageRequest.Limit, @offset = pageRequest.Limit * pageRequest.PageIndex }).ToList();
                //var datas = _dbContext.FwlbDto.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).Select(_ => _mapper.Map<FwlbDto>(_)).ToList();
                var pageData = new PagePc<object>(datas
                    , pageRequest.PageIndex + 1, pageRequest.Limit, count.Count, count.Count, count.Yzc, count.Wzc, count.Yjc, count.Wjc);
                var r = new RespRet<PagePc<object>>(true, "Ok", pageData);
                WriteSystemLog("housessqjz/search-fwlb", r, pageRequest);
                return r;
            }
            catch (Exception ex)
            {
                var res = new RespRet<PagePc<object>>(false, ex.ToString());
                WriteSystemLogError("housessqjz/search-fwlb", res, pageRequest);
                res.Msg = "系统异常";
                return res;
            }
        }






        /// <summary>
        /// 房屋列表
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("housessqjz/taskdata")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<FwlbDto>>), 200)]
        public RespRet<Page<object>> TaskData([FromBody] Fwlb pageRequest)
        {
            if (pageRequest == null)
            {
                return new RespRet<Page<object>>(false, "请传递参数");
            }
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<object>>(false, "PageIndex must >= 0");
            }
            var userNumber = this.CurrentUser();
            var user = _dbContext.ZmUser.FirstOrDefault(c => c.Number == userNumber && c.IsDelete != 1 && c.Disabled != 1);
            var a = JsonRegion(user.District);
            JObject obj = JObject.Parse(user.District);
            string RegionCode = (string)obj["RegionCode"];
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet<Page<object>>(false, "user not logined");
            }
            try
            {
                var sbSql = new StringBuilder();
                var sbSqlCount = new StringBuilder();
                if (user.RoleType == 2)
                {
                    sbSqlCount.Append("  select count(1) from  zm_task a  where taskrys like @number    ");
                    sbSql.Append(" select a.pch,a.year,a.id,a.taskname,to_char(a.create_on,'YYYY-MM-DD HH24:MI:SS') createon ,count(1) zcount,count(case when hyzt is null then 1 end) why,count(hyzt) yhy from  zm_task a left join (select *from  zm_taskdetail where number like @number) b on a.id=b.taskid where taskrys like @number  ");

                    if (!string.IsNullOrWhiteSpace(pageRequest.text))
                    {
                        sbSqlCount.Append(" and a.taskname like @taskname ");
                        sbSql.Append(" and a.taskname like @taskname ");
                    }
                    sbSqlCount.Append(" group by a.id,a.taskname,a.create_on ");
                    sbSql.Append(" group by a.id,a.taskname,a.create_on order by a.create_on desc ");
                }
                var count = _dbContext.Database.GetDbConnection().Query<int>(sbSqlCount.ToString(), new { @taskname = "%" + pageRequest.text + "%", @number = "%" + user.Qaakey + "%", @limit = pageRequest.Limit, @offset = pageRequest.Limit * pageRequest.PageIndex }).FirstOrDefault();
                var datas = _dbContext.Database.GetDbConnection().Query<object>(sbSql.ToString(), new { @taskname = "%" + pageRequest.text + "%", @number = "%" + user.Qaakey + "%", @limit = pageRequest.Limit, @offset = pageRequest.Limit * pageRequest.PageIndex }).ToList();
                var pageData = new Page<object>(datas
                 , pageRequest.PageIndex + 1, pageRequest.Limit, count);
                var r = new RespRet<Page<object>>(true, "Ok", pageData);
                WriteSystemLog("housessqjz/taskdata", r, pageRequest);
                return r;
            }
            catch (Exception ex)
            {
                var res = new RespRet<Page<object>>(false, ex.ToString());
                WriteSystemLogError("housessqjz/taskdata", res, pageRequest);
                res.Msg = "系统异常";
                return res;
            }
        }



        /// <summary>
        /// 房屋列表
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("housessqjz/taskdetaile")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<FwlbDto>>), 200)]
        public RespRet<Page<object>> TaskDetaile([FromBody] Fwlb pageRequest)
        {
            if (pageRequest == null)
            {
                return new RespRet<Page<object>>(false, "请传递参数");
            }
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<object>>(false, "PageIndex must >= 0");
            }
            if (string.IsNullOrWhiteSpace(pageRequest.taskid))
            {
                return new RespRet<Page<object>>(false, "任务id不能为空");
            }

            var userNumber = this.CurrentUser();
            var user = _dbContext.ZmUser.FirstOrDefault(c => c.Number == userNumber && c.IsDelete != 1 && c.Disabled != 1);
            var a = JsonRegion(user.District);
            JObject obj = JObject.Parse(user.District);
            string RegionCode = (string)obj["RegionCode"];
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet<Page<object>>(false, "user not logined");
            }
            try
            {
                if (user.RoleType == 2)
                {
                    string sbSqlCount = " select count(1) from zm_taskdetail a left join zm_buildings b on a.fwbh=b.fwbh   where taskid::text=@taskid and number=@number   ";
                    string sbSql = " select a.id,taskid,a.fwbh,b.address,b.hzxm ,to_char(create_on,'YYYY-MM-DD HH24:MI:SS') createon,case when hyzt is null then'未核验' when hyzt=1 then '已核验'end hyzt  from zm_taskdetail a left join zm_buildings b on a.fwbh=b.fwbh   where taskid::text=@taskid and number=@number    ";
                    if (!string.IsNullOrWhiteSpace(pageRequest.text))
                    {
                        sbSqlCount += " and  (a.fwbh like @text or b.address like @text or b.hzxm like @text)  ";
                        sbSql += " and (a.fwbh like @text or b.address like @text or b.hzxm like @text) ";
                    }


                    if (!string.IsNullOrWhiteSpace(pageRequest.Xzqdm))
                    {
                        sbSqlCount += " and b.xzqdm=@xzqdm   ";
                        sbSql += " and b.xzqdm=@xzqdm  ";
                    }
                    if (!string.IsNullOrWhiteSpace(pageRequest.Towndm))
                    {
                        sbSqlCount += " and b.towndm=@towndm   ";
                        sbSql += " and b.towndm=@towndm   ";
                    }
                    if (!string.IsNullOrWhiteSpace(pageRequest.Villagedm))
                    {
                        sbSqlCount += " and b.villagedm=@villagedm   ";
                        sbSql += " and b.villagedm=@villagedm  ";
                    }




                    if (pageRequest.hyzt >= 0)
                    {
                        if (pageRequest.hyzt == 0)
                        {
                            sbSqlCount += " and hyzt is null  ";
                            sbSql += " and hyzt is null ";
                        }
                        if (pageRequest.hyzt == 1)
                        {
                            sbSqlCount += " and hyzt=1 ";
                            sbSql += " and hyzt=1 ";
                        }
                    }
                    sbSql += "order by hyzt  limit @limit offset @offset";
                    var count = _dbContext.Database.GetDbConnection().Query<int>(sbSqlCount.ToString(), new {@xzqdm=pageRequest.Xzqdm,@towndm=pageRequest.Towndm,@villagedm=pageRequest.Villagedm,  @text = "%" + pageRequest.text + "%", @taskid = pageRequest.taskid, @number = user.Qaakey, @limit = pageRequest.Limit, @offset = pageRequest.Limit * pageRequest.PageIndex }).FirstOrDefault();
                    var datas = _dbContext.Database.GetDbConnection().Query<object>(sbSql.ToString(), new { @xzqdm = pageRequest.Xzqdm, @towndm = pageRequest.Towndm, @villagedm = pageRequest.Villagedm, @text = "%" + pageRequest.text + "%", @taskid = pageRequest.taskid, @number = user.Qaakey, @limit = pageRequest.Limit, @offset = pageRequest.Limit * pageRequest.PageIndex }).ToList();
                    var pageData = new Page<object>(datas
                     , pageRequest.PageIndex + 1, pageRequest.Limit, count);
                    var r = new RespRet<Page<object>>(true, "Ok", pageData);
                    WriteSystemLog("housessqjz/taskdata", r, pageRequest);
                    return r;
                }
                else
                {
                    var pageData = new Page<object>(new List<object>()
                     , pageRequest.PageIndex + 1, pageRequest.Limit, 0);
                    var r = new RespRet<Page<object>>(true, "Ok", pageData);
                    WriteSystemLog("housessqjz/taskdata", r, pageRequest);
                    return r;

                }

            }
            catch (Exception ex)
            {
                var res = new RespRet<Page<object>>(false, ex.ToString());
                WriteSystemLogError("housessqjz/taskdata", res, pageRequest);
                res.Msg = "系统异常";
                return res;
            }
        }


        /// <summary>
        /// 近七天为自查房屋
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("housessqjz/TheWeekNoCheckHouse")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<FwlbDto>>), 200)]
        public RespRet<int> TheWeekNoCheckHouse([FromBody] Fwlb pageRequest)
        {
            if (pageRequest == null)
            {
                return new RespRet<int>(false, "请传递参数");
            }
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<int>(false, "PageIndex must >= 0");
            }
            var userNumber = this.CurrentUser();
            var user = _dbContext.ZmUser.FirstOrDefault(c => c.Number == userNumber && c.IsDelete != 1 && c.Disabled != 1);
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet<int>(false, "user not logined");
            }
            try
            {
                var sbSqlCount = new StringBuilder();
                var sbSqlWhere = new StringBuilder();
                var sqlParams = new List<NpgsqlParameter>();
                sbSqlCount.Append($@"  SELECT
count(distinct b.fwbh) count	
FROM 
      zm_buildings  b     
LEFT JOIN 
     zm_pc_yh_sqjz  a ON b.fwbh = a.fwbh
LEFT JOIN  zm_pc_yh  d ON d.fwbh = b.fwbh  where 1=1  and  (case when	DATE_PART('day', now() -d.create_on)::text is null then 0 else DATE_PART('day', now() -d.create_on)::int end )>=7
  ");

                if (!string.IsNullOrWhiteSpace(pageRequest.Villagedm))
                {

                    sbSqlCount.Append($@" and b.villagedm=@villagedm ");

                    sqlParams.Add(new NpgsqlParameter("villagedm", $"{pageRequest.Villagedm}"));
                }
                if (!string.IsNullOrWhiteSpace(pageRequest.Towndm))
                {
                    sbSqlCount.Append($@" and b.towndm=@towndm ");
                    sqlParams.Add(new NpgsqlParameter("towndm", $"{pageRequest.Towndm}"));
                }
                if (!string.IsNullOrWhiteSpace(pageRequest.Xzqdm))
                {
                    sbSqlCount.Append($@" and b.xzqdm=@xzqdm ");
                    sqlParams.Add(new NpgsqlParameter("xzqdm", $"{pageRequest.Xzqdm}"));
                }
                var datas = _dbContext.CountClass.FromSqlRaw(sbSqlCount.ToString(), sqlParams.ToArray()).FirstOrDefault();
                var r = new RespRet<int>(true, "Ok", datas.Count);
                WriteSystemLog("housessqjz/TheWeekNoCheckHouse", r, pageRequest);
                return r;
            }
            catch (Exception ex)
            {
                var res = new RespRet<int>(false, ex.ToString());
                WriteSystemLogError("housessqjz/TheWeekNoCheckHouse", res, pageRequest);
                res.Msg = "系统异常";
                return res;
            }
        }



        /// <summary>
        /// 近七天为自查房屋详情
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("housessqjz/NoCheckHouseDetaile")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<FwlbDto>>), 200)]
        public RespRet<PagePc<FwlbDto>> NoCheckHouseDetaile([FromBody] Fwlb pageRequest)
        {
            if (pageRequest == null)
            {
                return new RespRet<PagePc<FwlbDto>>(false, "请传递参数");
            }
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<PagePc<FwlbDto>>(false, "PageIndex must >= 0");
            }
            var userNumber = this.CurrentUser();
            var user = _dbContext.ZmUser.FirstOrDefault(c => c.Number == userNumber && c.IsDelete != 1 && c.Disabled != 1);
            var a = JsonRegion(user.District);
            JObject obj = JObject.Parse(user.District);
            string RegionCode = (string)obj["RegionCode"];
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet<PagePc<FwlbDto>>(false, "user not logined");
            }
            try
            {
                var sbSql = new StringBuilder();
                var sbSqlCount = new StringBuilder();
                var yccbczsql = new StringBuilder();
                var sbSqlWhere = new StringBuilder();
                var sqlParams = new List<NpgsqlParameter>();

                string time = DateTime.Today
     .AddHours(23)
     .AddMinutes(59)
     .AddSeconds(59)
     .ToString("yyyy-MM-dd HH:mm:ss");

                string table_name = "zm_building_fwzt_" + DateTime.Now.Year;
                sqlParams.Add(new NpgsqlParameter("time", time));

                sbSql.Append($@" SELECT
 b.fwbh as id,
 max(date(a.create_on)::text) jcsj,
 max(date(d.create_on)::text) zcsj,
   max(b.address) address, 
   max(b.hzxm) hzxm, 
    b.fwbh, 
		  ST_X(ST_Centroid(ST_Collect(geom))) AS villagelongitude,
    ST_Y(ST_Centroid(ST_Collect(geom))) AS villagelatitude,
   max(a.pczt) pczt,
  max(st_asgeojson(geom)) AS geometry,
 CASE
        WHEN max(geom) IS NULL THEN NULL
        ELSE json_build_object(
            'type', 'Feature',
            'geometry', json_build_object(
                'type', 'MultiPolygon',
                'coordinates', ST_AsGeoJSON(max(geom))::json->'coordinates'
            ),
            'properties', json_build_object(
                'fwbh', max(b.fwbh),
                'address',max(b.address),
                'hzxm',max(b.hzxm)
            )
        )
    END AS feature,
	max(d.pczt)zczt,
 max(case when	DATE_PART('day', now() -d.create_on)::text is null then '' else DATE_PART('day', now() -d.create_on)::text end )AS day_difference		
FROM 
     (select * from zm_buildings t1 where fwbh  not in  (select fwbh From  {table_name} where final_create_on=@time  and final_fwzt is not null  ))  b     
LEFT JOIN 
     zm_pc_yh_sqjz  a ON b.fwbh = a.fwbh
LEFT JOIN  zm_pc_yh  d ON d.fwbh = b.fwbh  where 1=1  ");

                sbSqlCount.Append($@" SELECT
 count(distinct b.fwbh) count	,
  1 yjc,2 wjc,1 yzc,2 wzc
FROM 
      (select * from zm_buildings t1 where fwbh  not in  (select fwbh From  {table_name} where final_create_on=@time  and final_fwzt is not null  ))   b   
LEFT JOIN 
     zm_pc_yh_sqjz  a ON b.fwbh = a.fwbh
LEFT JOIN  zm_pc_yh  d ON d.fwbh = b.fwbh  where 1=1  ");
                yccbczsql.Append($@" SELECT
 count(1) count	,
1 yjc,2 wjc,1 yzc,2 wzc
FROM 
      (select * from zm_buildings t1 where fwbh  not in  (select fwbh From  {table_name} where final_create_on=@time  and final_fwzt is not null  ))  b   
LEFT JOIN 
     zm_pc_yh_sqjz  a ON b.fwbh = a.fwbh
LEFT JOIN  zm_pc_yh  d ON d.fwbh = b.fwbh  where 1=1  ");

                var CountSql = new StringBuilder();
                CountSql.Append($@"  SELECT
 count(case when d.pczt is null then 1 end) wzc,
 count(case when d.pczt is not null then 1 end) yzc,
 count(case when a.fwbh is null then 1 end) wjc,
 count(case when a.fwbh is not null then 1 end) yjc,
1 count 
FROM 
    (select * from zm_buildings t1 where fwbh  not in  (select fwbh From  {table_name} where final_create_on=@time  and final_fwzt is not null  ))  b  
LEFT JOIN 
   zm_pc_yh_sqjz a  ON b.fwbh = a.fwbh 
LEFT JOIN 
  zm_pc_yh  d ON d.fwbh = b.fwbh  where 1=1  ");
                if (!string.IsNullOrWhiteSpace(pageRequest.Villagedm))
                {
                    CountSql.Append($@" and b.villagedm=@villagedm ");
                    sbSql.Append($@" and b.villagedm=@villagedm ");
                    sbSqlCount.Append($@" and b.villagedm=@villagedm ");
                    yccbczsql.Append($@" and b.villagedm=@villagedm ");
                    sqlParams.Add(new NpgsqlParameter("villagedm", $"{pageRequest.Villagedm}"));
                }
                if (!string.IsNullOrWhiteSpace(pageRequest.Towndm))
                {
                    CountSql.Append($@" and b.towndm=@towndm ");
                    sbSql.Append($@" and b.towndm=@towndm ");
                    sbSqlCount.Append($@" and b.towndm=@towndm ");
                    yccbczsql.Append($@" and b.towndm=@towndm ");
                    sqlParams.Add(new NpgsqlParameter("towndm", $"{pageRequest.Towndm}"));
                }
                if (!string.IsNullOrWhiteSpace(pageRequest.Xzqdm))
                {
                    CountSql.Append($@" and b.xzqdm=@xzqdm ");
                    sbSql.Append($@" and b.xzqdm=@xzqdm ");
                    sbSqlCount.Append($@" and b.xzqdm=@xzqdm ");
                    yccbczsql.Append($@" and b.xzqdm=@xzqdm ");
                    sqlParams.Add(new NpgsqlParameter("xzqdm", $"{pageRequest.Xzqdm}"));
                }
                if (pageRequest.pczt != null)
                {
                    if (pageRequest.pczt == 0)
                    {
                        CountSql.Append($@" and a.pczt is null ");
                        sbSql.Append($@" and a.pczt is null ");
                        yccbczsql.Append($@" and a.pczt is null ");
                        sbSqlCount.Append($@" and a.pczt is null ");
                    }
                    else
                    {
                        CountSql.Append($@" and a.pczt=@pczt ");
                        sbSql.Append($@" and a.pczt=@pczt ");
                        sbSqlCount.Append($@" and a.pczt=@pczt ");
                        yccbczsql.Append($@" and a.pczt=@pczt ");
                        sqlParams.Add(new NpgsqlParameter("pczt", pageRequest.pczt));
                    }
                }

                if (pageRequest.ispc != null)
                {
                    if (pageRequest.ispc == 0)
                    {
                        CountSql.Append($@" and a.pczt is null ");
                        sbSql.Append($@" and a.pczt is null ");
                        yccbczsql.Append($@" and a.pczt is null ");
                        sbSqlCount.Append($@" and a.pczt is null ");
                    }
                    else
                    {
                        CountSql.Append($@" and a.pczt is not null ");
                        sbSql.Append($@" and a.pczt is not null ");
                        sbSqlCount.Append($@" and a.pczt is not null ");
                        yccbczsql.Append($@" and a.pczt is not null ");
                        sqlParams.Add(new NpgsqlParameter("pczt", pageRequest.ispc));
                    }
                }

                if (!string.IsNullOrWhiteSpace(pageRequest.text))
                {
                    CountSql.Append($@" and ( b.hzxm like @text or b.address like @text or b.fwbh like @text ) ");
                    sbSql.Append($@" and ( b.hzxm like @text or b.address like @text or b.fwbh like @text ) ");
                    sbSqlCount.Append($@" and ( b.hzxm like @text or b.address like @text or b.fwbh like @text ) ");
                    yccbczsql.Append($@" and ( b.hzxm like @text or b.address like @text or b.fwbh like @text ) ");
                    sqlParams.Add(new NpgsqlParameter("text", "%" + pageRequest.text + "%"));
                }

                if (!string.IsNullOrWhiteSpace(pageRequest.fwbh))
                {
                    CountSql.Append($@" and ( b.fwbh like @fwbh ) ");
                    sbSql.Append($@" and (  b.fwbh like @fwbh ) ");
                    sbSqlCount.Append($@" and (  b.fwbh like @fwbh ) ");
                    yccbczsql.Append($@" and (  b.fwbh like @fwbh ) ");
                    sqlParams.Add(new NpgsqlParameter("fwbh", "%" + pageRequest.fwbh + "%"));
                }

                if (!string.IsNullOrWhiteSpace(pageRequest.hzxm))
                {
                    CountSql.Append($@" and ( b.hzxm like @hzxm ) ");
                    sbSql.Append($@" and (  b.hzxm like @hzxm ) ");
                    sbSqlCount.Append($@" and (  b.hzxm like @hzxm ) ");
                    yccbczsql.Append($@" and (  b.hzxm like @hzxm ) ");
                    sqlParams.Add(new NpgsqlParameter("hzxm", "%" + pageRequest.hzxm + "%"));
                }

                if (!string.IsNullOrWhiteSpace(pageRequest.address))
                {
                    CountSql.Append($@" and ( b.address like @address ) ");
                    sbSql.Append($@" and (  b.address like @address ) ");
                    sbSqlCount.Append($@" and (  b.address like @address ) ");
                    yccbczsql.Append($@" and (  b.address like @address ) ");
                    sqlParams.Add(new NpgsqlParameter("address", "%" + pageRequest.address + "%"));
                }
                CountSql.Append($@"  and(case when DATE_PART('day', now() - d.create_on)::text is null then 0 else DATE_PART('day', now() - d.create_on)::int end )>= 7 ");
                sbSql.Append($@"  and(case when DATE_PART('day', now() - d.create_on)::text is null then 0 else DATE_PART('day', now() - d.create_on)::int end )>= 7 ");
                sbSqlCount.Append($@" and(case when DATE_PART('day', now() - d.create_on)::text is null then 0 else DATE_PART('day', now() - d.create_on)::int end )>= 7 ");
                yccbczsql.Append($@"  and(case when DATE_PART('day', now() - d.create_on)::text is null then 0 else DATE_PART('day', now() - d.create_on)::int end )>= 7 ");


                sbSql.Append($@" group by b.fwbh ");

                var count = _dbContext.FwlbCount.FromSqlRaw(sbSqlCount.ToString(), sqlParams.ToArray()).FirstOrDefault();
                var yccbcz = _dbContext.FwlbCount.FromSqlRaw(yccbczsql.ToString(), sqlParams.ToArray()).FirstOrDefault();
                var countpc = _dbContext.FwlbCount.FromSqlRaw(CountSql.ToString(), sqlParams.ToArray()).FirstOrDefault();

                //根据不同角色  进行不同排序
                if (user.RoleType == 2 || user.RoleType == 1 || user.RoleType == 3)
                {
                    sbSql.Append($@" order by max(d.create_on) desc NULLS LAST,max(a.create_on) desc NULLS LAST,b.fwbh ");
                }
                else
                {
                    sbSql.Append($@" 	order by max(case when DATE_PART('day', now() -a.create_on)::text is null then null else DATE_PART('day', now() -a.create_on) end )desc,max(case when DATE_PART('day', now() -d.create_on)::text is null then null else DATE_PART('day', now() -d.create_on) end )desc,b.fwbh
 ");
                }
                sbSql.Append($@" limit @limit offset @offset");
                sqlParams.Add(new NpgsqlParameter("limit", pageRequest.Limit));
                sqlParams.Add(new NpgsqlParameter("offset", pageRequest.Limit * pageRequest.PageIndex));
                var datas = _dbContext.FwlbDto.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).Select(_ => _mapper.Map<FwlbDto>(_)).ToList();
                var pageData = new PagePc<FwlbDto>(datas
                    , pageRequest.PageIndex + 1, pageRequest.Limit, count.Count, yccbcz.Count, countpc.Yzc, countpc.Wzc, countpc.Yjc, countpc.Wjc);
                var r = new RespRet<PagePc<FwlbDto>>(true, "Ok", pageData);
                WriteSystemLog("housessqjz/search-fwlb", r, pageRequest);
                return r;
            }
            catch (Exception ex)
            {
                var res = new RespRet<PagePc<FwlbDto>>(false, ex.ToString());
                WriteSystemLogError("housessqjz/search-fwlb", res, pageRequest);
                res.Msg = "系统异常";
                return res;
            }
        }





        /// <summary>
        /// 房屋隐患待督促
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("housessqjz/search-yhdx")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<PageCount<ZmPcYhLogDxDto2>>), 200)]
        public RespRet<PageCount<ZmPcYhLogDxDto2>> SearchAttrList([FromBody] PageHouseRequestInputYhdx pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<PageCount<ZmPcYhLogDxDto2>>(false, "PageIndex must >= 0");
            }
            var userNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet<PageCount<ZmPcYhLogDxDto2>>(false, "user not logined");
            }
            try
            {
                var user = _dbContext.ZmUser.FirstOrDefault(c => c.Number == userNumber && c.Disabled != 1);
                var a = JsonRegion(user.District);
                JObject obj = JObject.Parse(user.District);
                string RegionCode = (string)obj["RegionCode"];
                RegionCode = RegionCode.Substring(RegionCode.Length - 3) == "000" ? RegionCode.Substring(0, RegionCode.Length - 3) : RegionCode;
                var len = RegionCode.Length;
                var sbSql = new StringBuilder();
                var sbSqlWhere = new StringBuilder();
                var sqlParams = new List<NpgsqlParameter>();
                sbSql.Append($@" select a.id,a.fwbh,check_name,check_time,check_nickname as check_by,hzxm,c.address FROM zm_pc_yhlog_dx_sqjz a,zm_user_cj b,zm_buildings c where a.fwbh=c.fwbh and b.number=a.check_by and yhly=@yhly  and (zg_value=0 or zg_value is null ) ");
                if (pageRequest.CheckTime != null && pageRequest.CheckTime.Count() == 2)
                {
                    sbSql.Append($@" and check_time between  CAST(@starttime AS timestamp without time zone)  and CAST(@endtime AS timestamp without time zone) ");
                    sqlParams.Add(new NpgsqlParameter("starttime", $"{pageRequest.CheckTime[0]}"));
                    sqlParams.Add(new NpgsqlParameter("endtime", $"{pageRequest.CheckTime[1]}"));
                }
                if (len == 6)
                {
                    sbSql.Append($@" and a.xzqdm like @xzqdm ");
                    sqlParams.Add(new NpgsqlParameter("xzqdm", $"{"%" + RegionCode + "%"}"));
                }
                if (len == 9)
                {
                    sbSql.Append($@" and a.towndm like @towndm ");
                    sqlParams.Add(new NpgsqlParameter("towndm", $"{"%" + RegionCode + "%"}"));
                }
                if (len == 12)
                {
                    sbSql.Append($@" and a.villagedm like @villagedm ");
                    sqlParams.Add(new NpgsqlParameter("villagedm", $"{"%" + RegionCode + "%"}"));
                }
                sqlParams.Add(new NpgsqlParameter("yhly", $"{user.RoleType}"));
                var count = _dbContext.ZmPcYhLogDxDto.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).Count();


                sbSql.Append($@" order by a.create_on desc");
                sbSql.Append($@" limit @limit offset @offset");
                sqlParams.Add(new NpgsqlParameter("limit", pageRequest.Limit));
                sqlParams.Add(new NpgsqlParameter("offset", pageRequest.Limit * pageRequest.PageIndex));
                if (len == 6)
                {
                    sbSqlWhere.Append($@" and a.xzqdm like @xzqdm ");
                }
                if (len == 9)
                {
                    sbSqlWhere.Append($@" and a.towndm like @towndm ");
                }
                if (len == 12)
                {
                    sbSqlWhere.Append($@" and a.villagedm like @villagedm ");
                }
                var jcztsql = new StringBuilder();
                //获取各个状态的数量
                jcztsql.Append(@$"	
SELECT
(SELECT
  COUNT(CASE WHEN (zg_value = 0 or zg_value is null )  THEN 1 END) AS dzg
FROM zm_pc_yhlog_dx_sqjz a
WHERE   1=1 and yhly=@yhly {sbSqlWhere}
),
   COUNT(CASE WHEN jczt = '1' THEN 1 END) AS dfh,
  COUNT(CASE WHEN jczt = '2' then 1 end)AS fhtg
FROM zm_pc_yhlog_dxzgson_sqjz a
WHERE   1=1 and yhly=@yhly {sbSqlWhere} ");
                if (pageRequest.CheckTime != null && pageRequest.CheckTime.Count() == 2)
                {
                    jcztsql = new StringBuilder();
                    jcztsql.Append(@$" SELECT
(SELECT
  COUNT(CASE WHEN (zg_value = 0 or zg_value is null ) and check_time between  CAST(@starttime AS timestamp without time zone)  and CAST(@endtime AS timestamp without time zone)  THEN 1 END) AS dzg
FROM zm_pc_yhlog_dx_sqjz a
WHERE   1=1 and yhly=@yhly  {sbSqlWhere}
),
   COUNT(CASE WHEN jczt = '1' and CAST(zg_time AS timestamp without time zone) between  CAST(@starttime AS timestamp without time zone)  and CAST(@endtime AS timestamp without time zone) THEN 1 END) AS dfh,
  COUNT(CASE WHEN jczt = '2' and  CAST(fh_time AS timestamp without time zone) between  CAST(@starttime AS timestamp without time zone)  and CAST(@endtime AS timestamp without time zone) then 1 end)AS fhtg
FROM zm_pc_yhlog_dxzgson_sqjz a
WHERE    1=1 and yhly=@yhly  {sbSqlWhere}  ");
                    sqlParams.Add(new NpgsqlParameter("starttime", $"{pageRequest.CheckTime[0]}"));
                    sqlParams.Add(new NpgsqlParameter("endtime", $"{pageRequest.CheckTime[1]}"));
                }


                var num = _dbContext.Jcztnum.FromSqlRaw(jcztsql.ToString(), sqlParams.ToArray()).FirstOrDefault();

                var datas = _dbContext.ZmPcYhLogDxDto.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).Select(_ => _mapper.Map<ZmPcYhLogDxDto2>(_)).ToList();
                var pageData = new PageCount<ZmPcYhLogDxDto2>(datas
                    , pageRequest.PageIndex + 1, pageRequest.Limit, count, num.dzg, num.dfh, num.fhtg);
                var r = new RespRet<PageCount<ZmPcYhLogDxDto2>>(true, "Ok", pageData);
                WriteSystemLog("housessqjz/search-yhdx", r, pageRequest);
                return r;
            }
            catch (Exception ex)
            {
                var res = new RespRet<PageCount<ZmPcYhLogDxDto2>>(false, ex.ToString());
                WriteSystemLogError("housessqjz/search-yhdx", res, pageRequest);
                res.Msg = "系统异常";
                return res;
            }
        }




        /// <summary>
        /// 房屋隐患待复核、复核通过
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("housessqjz/search-yhdxbyjczt")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<PageCount<ZmPcYhLogDxZgDto>>), 200)]
        public RespRet<PageCount<ZmPcYhLogDxZgDto>> YhdxByStatus([FromBody] PageHouseRequestInputYhdx pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<PageCount<ZmPcYhLogDxZgDto>>(false, "PageIndex must >= 0");
            }

            var userNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet<PageCount<ZmPcYhLogDxZgDto>>(false, "user not logined");
            }
            try
            {
                var user = _dbContext.ZmUser.FirstOrDefault(c => c.Number == userNumber && c.Disabled != 1);
                var a = JsonRegion(user.District);
                JObject obj = JObject.Parse(user.District);
                string RegionCode = (string)obj["RegionCode"];
                RegionCode = RegionCode.Substring(RegionCode.Length - 3) == "000" ? RegionCode.Substring(0, RegionCode.Length - 3) : RegionCode;
                var len = RegionCode.Length;
                var sbSql = new StringBuilder();
                var sbSqlWhere = new StringBuilder();
                var sqlParams = new List<NpgsqlParameter>();
                sbSql.Append($@" select a.id,a.fwbh,zg_name zg_by,hzxm,zg_time,c.address,check_name,fh_time,fh_name fh_by FROM zm_pc_yhlog_dxzgson_sqjz a ,zm_buildings c where a.fwbh=c.fwbh  and yhly=@yhly      ");

                sqlParams.Add(new NpgsqlParameter("yhly", $"{user.RoleType}"));
                if (!string.IsNullOrWhiteSpace(pageRequest.Jczt))
                {
                    if (pageRequest.Jczt == "2")
                    {
                        sbSql = new StringBuilder();
                        sbSql.Append($@" select a.id,a.fwbh,zg_name zg_by,hzxm,zg_time,c.address,check_name,fh_time,fh_name fh_by FROM zm_pc_yhlog_dxzgson_sqjz a,zm_user_sqjz b ,zm_buildings c where a.fwbh=c.fwbh and  b.number=a.fh_by      ");
                        if (pageRequest.CheckTime != null && pageRequest.CheckTime.Count() == 2)
                        {
                            sbSql.Append($@" and CAST(fh_time AS timestamp without time zone) between  CAST(@starttime AS timestamp without time zone)  and CAST(@endtime AS timestamp without time zone)  ");
                            sqlParams.Add(new NpgsqlParameter("starttime", $"{pageRequest.CheckTime[0]}"));
                            sqlParams.Add(new NpgsqlParameter("endtime", $"{pageRequest.CheckTime[1]}"));
                        }
                    }
                    if (len == 6)
                    {
                        sbSql.Append($@" and a.xzqdm like @xzqdm ");
                        sqlParams.Add(new NpgsqlParameter("xzqdm", $"{"%" + RegionCode + "%"}"));
                    }
                    if (len == 9)
                    {
                        sbSql.Append($@" and a.towndm like @towndm ");
                        sqlParams.Add(new NpgsqlParameter("towndm", $"{"%" + RegionCode + "%"}"));
                    }
                    if (len == 12)
                    {
                        sbSql.Append($@" and a.villagedm like @villagedm ");
                        sqlParams.Add(new NpgsqlParameter("villagedm", $"{"%" + RegionCode + "%"}"));
                    }
                    if (pageRequest.Jczt == "1")
                    {
                        if (pageRequest.CheckTime != null && pageRequest.CheckTime.Count() == 2)
                        {
                            sbSql.Append($@" and CAST(zg_time AS timestamp without time zone) between  CAST(@starttime AS timestamp without time zone)  and CAST(@endtime AS timestamp without time zone)  ");
                            sqlParams.Add(new NpgsqlParameter("starttime", $"{pageRequest.CheckTime[0]}"));
                            sqlParams.Add(new NpgsqlParameter("endtime", $"{pageRequest.CheckTime[1]}"));
                        }
                    }
                    sbSql.Append($@" and jczt =@jczt  ");
                    sqlParams.Add(new NpgsqlParameter("jczt", $"{pageRequest.Jczt}"));
                }

                var count = _dbContext.ZmPcYhLogDxZgDto.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).Count();
                sbSql.Append($@" order by a.create_on desc");
                sbSql.Append($@" limit @limit offset @offset");
                sqlParams.Add(new NpgsqlParameter("limit", pageRequest.Limit));
                sqlParams.Add(new NpgsqlParameter("offset", pageRequest.Limit * pageRequest.PageIndex));


                if (len == 6)
                {
                    sbSqlWhere.Append($@" and a.xzqdm like @xzqdm ");
                }
                if (len == 9)
                {
                    sbSqlWhere.Append($@" and a.towndm like @towndm ");

                }
                if (len == 12)
                {
                    sbSqlWhere.Append($@" and a.villagedm like @villagedm ");

                }
                var jcztsql = new StringBuilder();
                //获取各个状态的数量
                jcztsql.Append(@$"	
SELECT
(SELECT
  COUNT(CASE WHEN (zg_value = 0 or zg_value is null )  THEN 1 END) AS dzg
FROM zm_pc_yhlog_dx_sqjz a
WHERE   1=1 and yhly=@yhly {sbSqlWhere}
),
   COUNT(CASE WHEN jczt = '1' THEN 1 END) AS dfh,
  COUNT(CASE WHEN jczt = '2' then 1 end)AS fhtg
FROM zm_pc_yhlog_dxzgson_sqjz a
WHERE   1=1 and yhly=@yhly {sbSqlWhere} ");
                if (pageRequest.CheckTime != null && pageRequest.CheckTime.Count() == 2)
                {
                    jcztsql = new StringBuilder();
                    jcztsql.Append(@$" SELECT
(SELECT
  COUNT(CASE WHEN (zg_value = 0 or zg_value is null ) and check_time between  CAST(@starttime AS timestamp without time zone)  and CAST(@endtime AS timestamp without time zone)  THEN 1 END) AS dzg
FROM zm_pc_yhlog_dx_sqjz a
WHERE   1=1 and yhly=@yhly {sbSqlWhere}
),
   COUNT(CASE WHEN jczt = '1' and CAST(zg_time AS timestamp without time zone) between  CAST(@starttime AS timestamp without time zone)  and CAST(@endtime AS timestamp without time zone) THEN 1 END) AS dfh,
  COUNT(CASE WHEN jczt = '2' and  CAST(fh_time AS timestamp without time zone) between  CAST(@starttime AS timestamp without time zone)  and CAST(@endtime AS timestamp without time zone) then 1 end)AS fhtg
FROM zm_pc_yhlog_dxzgson_sqjz a
WHERE    1=1 and yhly=@yhly {sbSqlWhere}  ");
                    sqlParams.Add(new NpgsqlParameter("starttime", $"{pageRequest.CheckTime[0]}"));
                    sqlParams.Add(new NpgsqlParameter("endtime", $"{pageRequest.CheckTime[1]}"));
                }
                var num = _dbContext.Jcztnum.FromSqlRaw(jcztsql.ToString(), sqlParams.ToArray()).FirstOrDefault();
                var datas = _dbContext.ZmPcYhLogDxZgDto.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).Select(_ => _mapper.Map<ZmPcYhLogDxZgDto>(_)).ToList();
                var pageData = new PageCount<ZmPcYhLogDxZgDto>(datas
                    , pageRequest.PageIndex + 1, pageRequest.Limit, count, num.dzg, num.dfh, num.fhtg);
                var r = new RespRet<PageCount<ZmPcYhLogDxZgDto>>(true, "Ok", pageData);
                WriteSystemLog("housessqjz/search-yhdxbyjczt", r, pageRequest);
                return r;
            }
            catch (Exception ex)
            {
                var res = new RespRet<PageCount<ZmPcYhLogDxZgDto>>(false, ex.ToString());
                WriteSystemLogError("housessqjz/search-yhdxbyjczt", res, pageRequest);
                res.Msg = "系统异常";
                return res;
            }
        }
        /// <summary>
        /// 获取隐患整改详情
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("housessqjz/search-yhxq")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<ZmPcYhLogDxDtoXq>), 200)]
        public RespRet<ZmPcYhLogDxDtoXq> Yhxq([FromQuery] string id)
        {
            var userNumber = this.CurrentUser();
            try
            {
                if (string.IsNullOrEmpty(userNumber))
                {
                    return new RespRet<ZmPcYhLogDxDtoXq>(false, "user not logined");
                }
                if (string.IsNullOrEmpty(id))
                {
                    return new RespRet<ZmPcYhLogDxDtoXq>(false, "id不能为空");
                }
                var user = _dbContext.ZmUser.FirstOrDefault(c => c.Number == userNumber && c.Disabled != 1);
                var sbSql = new StringBuilder();
                var sbSqlWhere = new StringBuilder();
                var sqlParams = new List<NpgsqlParameter>();

                sbSql.Append($@" select a.id,a.fwbh,a.check_id,a.check_name,check_zp,b.zg_value,zg_zp,a.zg_yhsyq_num,a.zg_ddc_num,check_sm  FROM zm_pc_yhlog_dxzgson_sqjz a,zm_pc_yhlog_dx_sqjz b where a.yhlog_dx_id=b.id  and yhly=@yhly   ");
                sbSql.Append($@" and a.id = @Id ");
                sqlParams.Add(new NpgsqlParameter("Id", $"{id}"));
                sqlParams.Add(new NpgsqlParameter("yhly", $"{user.RoleType}"));
                var from = _dbContext.ZmPcYhLogDxDtoXq.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).FirstOrDefault();
                if (from == null)
                {
                    var res = new RespRet<ZmPcYhLogDxDtoXq>(false, "未找到隐患信息，请传递正确ID", from);
                    WriteSystemLog("housessqjz/search-yhxq", res, id);
                    return res;
                }
                from.CheckZp = from.CheckZp == null ? null : string.Join("|", JsonStr2List(from.CheckZp));
                from.ZgZp = from.ZgZp == null ? null : string.Join("|", JsonStr2List(from.ZgZp));
                from.IsHaveYh = "是";

                var r = new RespRet<ZmPcYhLogDxDtoXq>(true, "Ok", from);
                WriteSystemLog("housessqjz/search-yhxq", r, id);
                return r;
            }
            catch (Exception ex)
            {
                var res = new RespRet<ZmPcYhLogDxDtoXq>(false, ex.ToString());
                WriteSystemLogError("housessqjz/search-yhxq", res, id);
                res.Msg = "系统异常";
                return res;
            }
        }




        /// <summary>
        /// 复核
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("housessqjz/search-fh")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<int>), 200)]
        public RespRet<int> Fh([FromBody] Fh model)
        {
            var userNumber = this.CurrentUser();
            using (var transaction = _dbContext.Database.BeginTransaction())
            {
                try
                {
                    if (string.IsNullOrEmpty(userNumber))
                    {
                        return new RespRet<int>(false, "user not logined");
                    }
                    if (model == null)
                    {
                        return new RespRet<int>(false, "请传递参数");
                    }

                    if (string.IsNullOrEmpty(model.id))
                    {
                        return new RespRet<int>(false, "id不能为空");
                    }
                    if (model.status != 0 && model.status != 1)
                    {
                        return new RespRet<int>(false, "复核只能选择通过或不通过");
                    }
                    var r = _dbContext.ZmPcYhlogDxzgsonSqjz.FirstOrDefault(c => c.Id == model.id);
                    if (r == null)
                    {
                        var res = new RespRet<int>(false, "未找到隐患，请传递正确id");
                        WriteSystemLog("housessqjz/search-fh", res, model);
                        return res;
                    }
                    var user = _dbContext.ZmUser.FirstOrDefault(c => c.Number == userNumber && c.IsDelete != 1 && c.Disabled != 1);
                    if (user == null)
                    {
                        var res = new RespRet<int>(false, "未找用户信息");
                        WriteSystemLog("housessqjz/search-fh", res, model);
                        return res;
                    }
                    var dx = _dbContext.ZmPcYhLogDxSqjz.FirstOrDefault(c => c.Id == r.YhlogDxId);
                    if (dx != null)
                    {
                        r.FhZt = model.status;
                        r.FhSm = model.fhsm;
                        r.FhTime = DateTime.Now.ToString();
                        r.FhBy = userNumber;
                        r.FhName = user.Nickname;
                        dx.FhZt = model.status;

                        if (model.status == 0)
                        {
                            dx.Jczt = "2";
                            r.Jczt = "2";
                            var yh = _dbContext.ZmPcYhLogDxSqjz.Where(c => c.Fwbh == r.Fwbh && c.Id != r.YhlogDxId && c.FhZt != 0 && c.YhlogId == dx.YhlogId).ToList();
                            if (yh == null || yh.Count == 0)
                            {
                                var jclog = _dbContext.ZmPcYhSqjz.FirstOrDefault(c => c.Fwbh == r.Fwbh);
                                if (jclog != null)
                                {
                                    jclog.Pczt = 1;
                                    _dbContext.Update(jclog);
                                    if (_dbContext.SaveChanges() == 0)
                                    {
                                        WriteSystemLog("housessqjz/search-fh", new RespRet<int>(false, "修改ZmPcYhCj出错", 0), model);
                                        return new RespRet<int>(false, "复核失败", 0);
                                    }
                                }

                            }
                        }
                        else
                        {
                            dx.ZgValue = 0;
                            dx.Jczt = null;
                            r.Jczt = null;
                        }
                        _dbContext.Update(r);
                        _dbContext.Update(dx);
                        if (_dbContext.SaveChanges() == 2)
                        {
                            transaction.Commit();
                            var res = new RespRet<int>(true, "操作成功");
                            WriteSystemLog("housessqjz/search-fh", res, model);
                            return res;
                        }
                        else
                        {
                            transaction.Rollback();
                            var res = new RespRet<int>(false, "操作失败");
                            WriteSystemLog("housessqjz/search-fh", res, model);
                            return res;
                        }
                    }
                    else
                    {
                        var res = new RespRet<int>(false, "未找到隐患，请传递正确id");
                        WriteSystemLog("housessqjz/search-fh", res, model);
                        return res;
                    }
                }
                catch (Exception ex)
                {
                    var res = new RespRet<int>(false, ex.ToString());
                    WriteSystemLogError("housessqjz/search-fh", res, model);
                    res.Msg = "系统异常";
                    return res;
                }
            }
        }



        /// <summary>
        /// 对隐患数据进行整改
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("housessqjz/update-yhzg")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<ZmPcYhLogDxDtoXq>), 200)]
        public RespRet<int> Yhzg([FromBody] ZmPcYhlogDxzgson model)
        {

            using (var transaction = _dbContext.Database.BeginTransaction())
            {
                var userNumber = this.CurrentUser();
                try
                {
                    if (string.IsNullOrEmpty(userNumber))
                    {
                        return new RespRet<int>(false, "user not logined");
                    }
                    var yh = _dbContext.ZmPcYhLogDxSqjz.FirstOrDefault(c => c.Id == model.Id);
                    if (yh != null)
                    {
                        if (yh.ZgValue == 1)
                        {
                            transaction.Rollback();
                            var r = new RespRet<int>(false, "该隐患已整改，无需重复操作");
                            WriteSystemLog("housessqjz/search-yhzg", r, model);
                            return r;
                        }

                        //村级检查隐患
                        yh.ZgValue = 1;
                        _dbContext.Update(yh);
                        var res = _dbContext.SaveChanges();
                        if (res > 0)
                        {
                            var add = _mapper.Map<ZmPcYhlogDxzgsonSqjz>(yh);
                            add.ZgZp = model.ZgZp == null ? null : JsonConvert.SerializeObject(model.ZgZp.Split("|"));
                            add.ZgDdcNum = model.ZgDdcNum;
                            add.ZgYhsyqNum = model.ZgYhsyqNum;
                            add.Jczt = "1";
                            _dbContext.Add(add);
                            int i = _dbContext.SaveChanges();
                            if (i > 0)
                            {
                                transaction.Commit();
                                var r = new RespRet<int>(true, "Ok", i);
                                WriteSystemLog("housessqjz/search-yhzg", r, model);
                                return r;
                            }
                            else
                            {
                                transaction.Rollback();
                                var r = new RespRet<int>(false, "操作失败");
                                WriteSystemLog("housessqjz/search-yhzg", r, model);
                                return r;
                            }
                        }
                        else
                        {
                            transaction.Rollback();
                            var r = new RespRet<int>(false, "操作失败");
                            WriteSystemLog("housessqjz/search-yhzg", r, model);
                            return r;
                        }
                    }
                    //从村民找
                    var yhcm = _dbContext.ZmPcYhLogDx.FirstOrDefault(c => c.Id == model.Id);
                    if (yhcm != null)
                    {
                        if (yhcm.ZgValue == 1)
                        {
                            transaction.Rollback();
                            var r = new RespRet<int>(false, "该隐患已整改，无需重复操作");
                            WriteSystemLog("housessqjz/search-yhzg", r, model);
                            return r;
                        }
                        yhcm.ZgValue = 1;
                        _dbContext.Update(yhcm);
                        var res = _dbContext.SaveChanges();
                        if (res > 0)
                        {
                            var add = _mapper.Map<ZmPcYhlogDxzgson>(yhcm);
                            add.ZgZp = model.ZgZp == null ? null : JsonConvert.SerializeObject(model.ZgZp.Split("|"));
                            add.ZgDdcNum = model.ZgDdcNum;
                            add.ZgYhsyqNum = model.ZgYhsyqNum;
                            _dbContext.Add(add);
                            int i = _dbContext.SaveChanges();
                            if (i > 0)
                            {
                                transaction.Commit();
                                var r = new RespRet<int>(true, "Ok", i);
                                WriteSystemLog("housessqjz/search-yhzg", r, model);
                                return r;
                            }
                            else
                            {
                                transaction.Rollback();
                                var r = new RespRet<int>(false, "操作失败");
                                WriteSystemLog("housessqjz/search-yhzg", r, model);
                                return r;
                            }
                        }
                        else
                        {
                            transaction.Rollback();
                            var r = new RespRet<int>(false, "操作失败");
                            WriteSystemLog("housessqjz/search-yhzg", r, model);
                            return r;
                        }
                    }
                    else
                    {
                        transaction.Rollback();
                        var r = new RespRet<int>(false, "未找到该隐患，请刷新重试");
                        WriteSystemLog("housessqjz/search-yhzg", r, model);
                        return r;
                    }
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    var res = new RespRet<int>(false, ex.ToString());
                    WriteSystemLogError("housessqjz/search-yhzg", res, model);
                    res.Msg = "系统异常";
                    return res;
                }
            }
        }


        /// <summary>
        /// 房屋信息填报
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("housessqjz/update-yhzc")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<int>), 200)]
        public RespRet<int> UpdateHouseByFwbh([FromBody] UpdateHouseSqjzDto from)
        {
            var userNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet<int>(false, "user not logined");
            }
            if (from == null || from.ZmPcBase == null)
            {
                return new RespRet<int>(false, "请正确传递参数");
            }
            if (from.ZmPcYh != null)
            {
                from.ZmPcYh.Pczt = 0;
            }
            try
            {
                var basemsg2 = _dbContext.ZmBuildings.FirstOrDefault(u => u.Fwbh == from.ZmPcBase.Fwbh);
                if (basemsg2 == null)
                {
                    var r1 = new RespRet<int>(false, "房屋不存在");
                    WriteSystemLog("housessqjz/update-yhzc", r1, from);
                    return r1;
                }
                var user = _dbContext.ZmUser.FirstOrDefault(c => c.Number == userNumber && c.IsDelete != 1 && c.Disabled != 1);

                //在当前用户抽检任务下
                var zc_detaile = _dbContext.ZmTaskDetail.FirstOrDefault(c => c.Fwbh == from.ZmPcBase.Fwbh && c.Number == user.Qaakey);
                if (zc_detaile != null && user.RoleType == 2)  //只有市级 才能更改
                {
                    from.ZmPcBase.iscj = 1;
                    from.ZmPcBase.DetaileId = zc_detaile.Id;
                }
                
                var taskcj = _dbContext.ZmTaskDetail.FirstOrDefault(c => c.Fwbh == from.ZmPcBase.Fwbh);
                bool flag = false;
                //在抽检任务当中
                if (taskcj != null)  
                {
                    flag = true;
                }
                var id = Guid.NewGuid().ToString();
                var pc = _dbContext.ZmPcBaseSqjz.AsNoTracking().FirstOrDefault(u => u.Fwbh == from.ZmPcBase.Fwbh && u.IsDelete != 1 && u.Yhly == user.RoleType);
                //之前没有采集过，设置默认信息
                from.ZmPcBase.CreateBy = user.Number;
                from.ZmPcBase.CreateName = user.Nickname;
                from.ZmPcBase.CreateOn = DateTime.Now;
                from.ZmPcBase.CreateIp = this.IpAddress();
                from.ZmPcBase.IsDelete = null;
                from.ZmPcBase.DeleteBy = null;
                from.ZmPcBase.DeleteOn = null;
                from.ZmPcBase.DeleteIp = null;
                from.ZmPcBase.Id = id;
                from.ZmPcBase.Fwbh = from.ZmPcBase.Fwbh;
                from.ZmPcBase.Hzxm = basemsg2.Hzxm;
                from.ZmPcBase.Yhly = user.RoleType;
                from.ZmPcBase.Xzqdm = basemsg2.Xzqdm;
                from.ZmPcBase.Town = basemsg2.Towndm;
                from.ZmPcBase.Village = basemsg2.Villagedm;
                from.ZmPcBase.Xzq = basemsg2.Xzq;
                from.ZmPcBase.Towndm = basemsg2.Town;
                from.ZmPcBase.Villagedm = basemsg2.Village;
                from.ZmPcBase.CreateName = user.Nickname;
                from.ZmPcBase.Address = basemsg2.Address;
                from.ZmPcBase.Pcsj = DateTime.Now;
                from.ZmPcBase.SfmzstdPhoto = from.ZmPcBase.SfmzstdPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcBase.SfmzstdPhoto.Split("|"));
                from.ZmPcBase.SfmzstdZgPhoto = from.ZmPcBase.SfmzstdZgPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcBase.SfmzstdZgPhoto.Split("|"));


                from.ZmPcBase.SfczjxgbczzrPhoto = (from.ZmPcBase.SfczjxgbczzrPhoto == null || from.ZmPcBase.SfczjxgbczzrPhoto == "") ? null : JsonConvert.SerializeObject(from.ZmPcBase.SfczjxgbczzrPhoto.Split("|"));
                from.ZmPcBase.SfczjxgbczzrZgPhoto = (from.ZmPcBase.SfczjxgbczzrZgPhoto == null || from.ZmPcBase.SfczjxgbczzrZgPhoto == "") ? null : JsonConvert.SerializeObject(from.ZmPcBase.SfczjxgbczzrZgPhoto.Split("|"));


                from.ZmPcBase.SstdsyyrkrclzxPhoto = (from.ZmPcBase.SstdsyyrkrclzxPhoto == null || from.ZmPcBase.SstdsyyrkrclzxPhoto == "") ? null : JsonConvert.SerializeObject(from.ZmPcBase.SstdsyyrkrclzxPhoto.Split("|"));
                from.ZmPcBase.SstdsyyrkrclzxZgPhoto = (from.ZmPcBase.SstdsyyrkrclzxZgPhoto == null || from.ZmPcBase.SstdsyyrkrclzxZgPhoto == "") ? null : JsonConvert.SerializeObject(from.ZmPcBase.SstdsyyrkrclzxZgPhoto.Split("|"));




                from.ZmPcBase.GryssdcsszblyyqksddpPhoto = (from.ZmPcBase.GryssdcsszblyyqksddpPhoto == null || from.ZmPcBase.GryssdcsszblyyqksddpPhoto == "") ? null : JsonConvert.SerializeObject(from.ZmPcBase.GryssdcsszblyyqksddpPhoto.Split("|"));
                from.ZmPcBase.GryssdcsszblyyqksddpZgPhoto = (from.ZmPcBase.GryssdcsszblyyqksddpZgPhoto == null || from.ZmPcBase.GryssdcsszblyyqksddpZgPhoto == "") ? null : JsonConvert.SerializeObject(from.ZmPcBase.GryssdcsszblyyqksddpZgPhoto.Split("|"));



                from.ZmPcBase.FwyfwdddzxccdsssfayqjshsfPhoto = (from.ZmPcBase.FwyfwdddzxccdsssfayqjshsfPhoto == null || from.ZmPcBase.FwyfwdddzxccdsssfayqjshsfPhoto == "") ? null : JsonConvert.SerializeObject(from.ZmPcBase.FwyfwdddzxccdsssfayqjshsfPhoto.Split("|"));
                from.ZmPcBase.FwyfwdddzxccdsssfayqjshsfZgPhoto = (from.ZmPcBase.FwyfwdddzxccdsssfayqjshsfZgPhoto == null || from.ZmPcBase.FwyfwdddzxccdsssfayqjshsfZgPhoto == "") ? null : JsonConvert.SerializeObject(from.ZmPcBase.FwyfwdddzxccdsssfayqjshsfZgPhoto.Split("|"));



                //隐患识别及数据校验
                var yhlog_id = Guid.NewGuid().ToString();
                var list = new List<ZmPcYhLogDxSqjz>();
                var listson = new List<ZmPcYhlogDxzgsonSqjz>();

                //判断基础表里面的隐患
                if (from.ZmPcBase != null)
                {
                    //彩钢板建筑是否出租住人    wdwhjgfjgqsyyrkrgbdj = 1   THEN '存在彩钢板建筑出租住人'
                    if (from.ZmPcBase.Wdwhjgfjgqsyyrkrgbdj == 1 || from.ZmPcBase.Wdwhjgfjgqsyyrkrgbdj == 0)
                    {
                        //如果等于1，描述不能为空
                        if (from.ZmPcBase.Wdwhjgfjgqsyyrkrgbdj == 1)
                        {
                            if (string.IsNullOrWhiteSpace(from.ZmPcBase.SfczjxgbczzrPhoto))
                            {
                                return new RespRet<int>(false, "存在夹芯彩钢板出租住人照片不能为空");
                            }
                            from.ZmPcYh.Pczt += 1;
                            //整改了也需要往数据库插数据，标记已整改
                            var ddcid = Guid.NewGuid().ToString();
                            list.Add(new ZmPcYhLogDxSqjz
                            {
                                Fwbh = from.ZmPcBase.Fwbh,
                                Id = ddcid,
                                YhlogId = from.ZmPcBase.Id, //这个需要确认  挂接base的
                                Jcly = user.RoleType,
                                CheckId = "wdwhjgfjgqsyyrkrgbdj",
                                CheckName = "存在夹芯彩钢板出租住人情况",
                                CheckSm = from.ZmPcBase.SfczjxgbczzrMsg,
                                CheckBy = userNumber,
                                CheckTime = DateTime.Now,
                                CheckZp = from.ZmPcBase.SfczjxgbczzrPhoto,
                                CreateOn = DateTime.Now,
                                ZgValue = from.ZmPcBase.SfczjxgbczzrZgqk == null ? 0 : from.ZmPcBase.SfczjxgbczzrZgqk,
                                Xzq = basemsg2.Xzq,
                                Xzqdm = basemsg2.Xzqdm,
                                Town = basemsg2.Town,
                                Towndm = basemsg2.Towndm,
                                Village = basemsg2.Village,
                                Villagedm = basemsg2.Villagedm,
                                CheckNickname = user.Nickname

                            });
                            //如果整改
                            if (from.ZmPcBase.SfczjxgbczzrZgqk == 1)
                            {
                                from.ZmPcYh.Pczt -= 1;
                                if (string.IsNullOrWhiteSpace(from.ZmPcBase.SfczjxgbczzrZgPhoto))
                                {
                                    return new RespRet<int>(false, "存在夹芯彩钢板出租住人的整改照片不能为空");
                                }
                                listson.Add(new ZmPcYhlogDxzgsonSqjz
                                {
                                    CheckId = "wdwhjgfjgqsyyrkrgbdj",
                                    CheckName = "存在夹芯彩钢板出租住人情况",
                                    CreateOn = DateTime.Now,
                                    Fwbh = basemsg2.Fwbh,
                                    Id = Guid.NewGuid().ToString(),
                                    YhlogDxId = ddcid,  //隐患的id
                                    ZgBy = basemsg2.Hzxm,
                                    Zglx = "2",
                                    ZgTime = DateTime.Now.ToString(),
                                    ZgZp = from.ZmPcBase.SfczjxgbczzrZgPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcBase.SfczjxgbczzrZgPhoto.Split("|")),
                                    Xzq = basemsg2.Xzq,
                                    Xzqdm = basemsg2.Xzqdm,
                                    Town = basemsg2.Town,
                                    Towndm = basemsg2.Towndm,
                                    Village = basemsg2.Village,
                                    Villagedm = basemsg2.Villagedm
                                });
                            }

                        }
                    }
                    else
                    {
                        return new RespRet<int>(false, "是否存在夹芯彩钢板出租住人只能为1或0");
                    }

                    //建设人员疏散通道     jsrysstd = 是   THEN '是否按标准疏散通道'
                    if (from.ZmPcBase.Jsrysstd =="是" || from.ZmPcBase.Jsrysstd =="否")
                    {
                        //如果等于1，描述不能为空
                        if (from.ZmPcBase.Jsrysstd =="否")
                        {
                            if (string.IsNullOrWhiteSpace(from.ZmPcBase.SfmzstdPhoto))
                            {
                                return new RespRet<int>(false, "是否按标准建设疏散通道照片不能为空");
                            }
                            from.ZmPcYh.Pczt += 1;
                            //整改了也需要往数据库插数据，标记已整改
                            var ddcid = Guid.NewGuid().ToString();
                            list.Add(new ZmPcYhLogDxSqjz
                            {
                                Fwbh = from.ZmPcBase.Fwbh,
                                Id = ddcid,
                                YhlogId = from.ZmPcBase.Id, //这个需要确认  挂接base的
                                Jcly = user.RoleType,
                                CheckId = "jsrysstd",
                                CheckName = "未按标准建设疏散通道",
                                CheckSm = from.ZmPcBase.SfmzstdMsg,
                                CheckBy = userNumber,
                                CheckTime = DateTime.Now,
                                CheckZp = from.ZmPcBase.SfmzstdPhoto,
                                CreateOn = DateTime.Now,
                                ZgValue = from.ZmPcBase.SfmzstdZgqk == null ? 0 : from.ZmPcBase.SfmzstdZgqk,
                                Xzq = basemsg2.Xzq,
                                Xzqdm = basemsg2.Xzqdm,
                                Town = basemsg2.Town,
                                Towndm = basemsg2.Towndm,
                                Village = basemsg2.Village,
                                Villagedm = basemsg2.Villagedm,
                                CheckNickname = user.Nickname

                            });
                            //如果整改
                            if (from.ZmPcBase.SfmzstdZgqk == 1)
                            {
                                from.ZmPcYh.Pczt -= 1;
                                if (string.IsNullOrWhiteSpace(from.ZmPcBase.SfmzstdZgPhoto))
                                {
                                    return new RespRet<int>(false, "是否按标准建设疏散通道整改照片不能为空");
                                }
                                listson.Add(new ZmPcYhlogDxzgsonSqjz
                                {
                                    CheckId = "jsrysstd",
                                    CheckName = "未按标准建设疏散通道",
                                    CreateOn = DateTime.Now,
                                    Fwbh = basemsg2.Fwbh,
                                    Id = Guid.NewGuid().ToString(),
                                    YhlogDxId = ddcid,  //隐患的id
                                    ZgBy = basemsg2.Hzxm,
                                    Zglx = "2",
                                    ZgTime = DateTime.Now.ToString(),
                                    ZgZp = from.ZmPcBase.SfmzstdZgPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcBase.SfmzstdZgPhoto.Split("|")),
                                    Xzq = basemsg2.Xzq,
                                    Xzqdm = basemsg2.Xzqdm,
                                    Town = basemsg2.Town,
                                    Towndm = basemsg2.Towndm,
                                    Village = basemsg2.Village,
                                    Villagedm = basemsg2.Villagedm
                                });
                            }

                        }
                    }
                    else
                    {
                        return new RespRet<int>(false, "是否按标准疏散通道只能为是或否");
                    }


                    //疏散通道使用易燃可燃材料装修（1是0否）   sstdsyyrkrclzx
                    if (from.ZmPcBase.Sstdsyyrkrclzx == 1 || from.ZmPcBase.Sstdsyyrkrclzx == 0)
                    {
                        //如果等于1，描述不能为空
                        if (from.ZmPcBase.Sstdsyyrkrclzx == 1)
                        {
                            if (string.IsNullOrWhiteSpace(from.ZmPcBase.SstdsyyrkrclzxPhoto))
                            {
                                return new RespRet<int>(false, "疏散通道使用易燃可燃材料装修照片不能为空");
                            }
                            from.ZmPcYh.Pczt += 1;
                            //整改了也需要往数据库插数据，标记已整改
                            var ddcid = Guid.NewGuid().ToString();
                            list.Add(new ZmPcYhLogDxSqjz
                            {
                                Fwbh = from.ZmPcBase.Fwbh,
                                Id = ddcid,
                                YhlogId = from.ZmPcBase.Id, //这个需要确认  挂接base的
                                Jcly = user.RoleType,
                                CheckId = "sstdsyyrkrclzx",
                                CheckName = "疏散通道使用易燃可燃材料装修",
                                CheckSm = from.ZmPcBase.SstdsyyrkrclzxMsg,
                                CheckBy = userNumber,
                                CheckTime = DateTime.Now,
                                CheckZp = from.ZmPcBase.SstdsyyrkrclzxPhoto,
                                CreateOn = DateTime.Now,
                                ZgValue = from.ZmPcBase.SstdsyyrkrclzxZgqk == null ? 0 : from.ZmPcBase.SstdsyyrkrclzxZgqk,
                                Xzq = basemsg2.Xzq,
                                Xzqdm = basemsg2.Xzqdm,
                                Town = basemsg2.Town,
                                Towndm = basemsg2.Towndm,
                                Village = basemsg2.Village,
                                Villagedm = basemsg2.Villagedm,
                                CheckNickname = user.Nickname

                            });
                            //如果整改
                            if (from.ZmPcBase.SstdsyyrkrclzxZgqk == 1)
                            {
                                from.ZmPcYh.Pczt -= 1;
                                if (string.IsNullOrWhiteSpace(from.ZmPcBase.SstdsyyrkrclzxZgPhoto))
                                {
                                    return new RespRet<int>(false, "疏散通道使用易燃可燃材料装修的整改照片不能为空");
                                }
                                listson.Add(new ZmPcYhlogDxzgsonSqjz
                                {
                                    CheckId = "sstdsyyrkrclzx",
                                    CheckName = "疏散通道使用易燃可燃材料装修",
                                    CreateOn = DateTime.Now,
                                    Fwbh = basemsg2.Fwbh,
                                    Id = Guid.NewGuid().ToString(),
                                    YhlogDxId = ddcid,  //隐患的id
                                    ZgBy = basemsg2.Hzxm,
                                    Zglx = "2",
                                    ZgTime = DateTime.Now.ToString(),
                                    ZgZp = from.ZmPcBase.SstdsyyrkrclzxZgPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcBase.SstdsyyrkrclzxZgPhoto.Split("|")),
                                    Xzq = basemsg2.Xzq,
                                    Xzqdm = basemsg2.Xzqdm,
                                    Town = basemsg2.Town,
                                    Towndm = basemsg2.Towndm,
                                    Village = basemsg2.Village,
                                    Villagedm = basemsg2.Villagedm
                                });
                            }

                        }
                    }
                    else
                    {
                        return new RespRet<int>(false, "疏散通道使用易燃可燃材料装修只能为1或0");
                    }


                    //供人员疏散的场院、内院、天井设置不利于烟气扩散的顶棚南棚     Gryssdcsszblyyqksddp = 1   THEN '顶棚南棚'
                    if (from.ZmPcBase.Gryssdcsszblyyqksddp == 1 || from.ZmPcBase.Gryssdcsszblyyqksddp == 0)
                    {
                        //如果等于1，描述不能为空
                        if (from.ZmPcBase.Gryssdcsszblyyqksddp == 1)
                        {
                            if (string.IsNullOrWhiteSpace(from.ZmPcBase.GryssdcsszblyyqksddpPhoto))
                            {
                                return new RespRet<int>(false, "供人员疏散的场院、内院、天井设置不利于烟气扩散的顶棚南棚照片不能为空");
                            }
                            from.ZmPcYh.Pczt += 1;
                            //整改了也需要往数据库插数据，标记已整改
                            var ddcid = Guid.NewGuid().ToString();
                            list.Add(new ZmPcYhLogDxSqjz
                            {
                                Fwbh = from.ZmPcBase.Fwbh,
                                Id = ddcid,
                                YhlogId = from.ZmPcBase.Id, //这个需要确认  挂接base的
                                Jcly = user.RoleType,
                                CheckId = "gryssdcsszblyyqksddp",
                                CheckName = "供人员疏散的场院、内院、天井设置不利于烟气扩散的顶棚南棚",
                                CheckSm = from.ZmPcBase.GryssdcsszblyyqksddpMsg,
                                CheckBy = userNumber,
                                CheckTime = DateTime.Now,
                                CheckZp = from.ZmPcBase.GryssdcsszblyyqksddpPhoto,
                                CreateOn = DateTime.Now,
                                ZgValue = from.ZmPcBase.GryssdcsszblyyqksddpZgqk == null ? 0 : from.ZmPcBase.GryssdcsszblyyqksddpZgqk,
                                Xzq = basemsg2.Xzq,
                                Xzqdm = basemsg2.Xzqdm,
                                Town = basemsg2.Town,
                                Towndm = basemsg2.Towndm,
                                Village = basemsg2.Village,
                                Villagedm = basemsg2.Villagedm,
                                CheckNickname = user.Nickname

                            });
                            //如果整改
                            if (from.ZmPcBase.GryssdcsszblyyqksddpZgqk == 1)
                            {
                                from.ZmPcYh.Pczt -= 1;
                                if (string.IsNullOrWhiteSpace(from.ZmPcBase.GryssdcsszblyyqksddpZgPhoto))
                                {
                                    return new RespRet<int>(false, "供人员疏散的场院、内院、天井设置不利于烟气扩散的顶棚南棚的整改照片不能为空");
                                }
                                listson.Add(new ZmPcYhlogDxzgsonSqjz
                                {
                                    CheckId = "gryssdcsszblyyqksddp",
                                    CheckName = "供人员疏散的场院、内院、天井设置不利于烟气扩散的顶棚南棚",
                                    CreateOn = DateTime.Now,
                                    Fwbh = basemsg2.Fwbh,
                                    Id = Guid.NewGuid().ToString(),
                                    YhlogDxId = ddcid,  //隐患的id
                                    ZgBy = basemsg2.Hzxm,
                                    Zglx = "2",
                                    ZgTime = DateTime.Now.ToString(),
                                    ZgZp = from.ZmPcBase.GryssdcsszblyyqksddpZgPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcBase.GryssdcsszblyyqksddpZgPhoto.Split("|")),
                                    Xzq = basemsg2.Xzq,
                                    Xzqdm = basemsg2.Xzqdm,
                                    Town = basemsg2.Town,
                                    Towndm = basemsg2.Towndm,
                                    Village = basemsg2.Village,
                                    Villagedm = basemsg2.Villagedm
                                });
                            }

                        }
                    }
                    else
                    {
                        return new RespRet<int>(false, "供人员疏散的场院、内院、天井设置不利于烟气扩散的顶棚南棚只能为1或0");
                    }

                    //服务充电设施服务于房屋的电动自行车充电设施是否按要求建设和收费  是 1是0否2不涉及 
                    if (from.ZmPcBase.Fwyfwdddzxccdsssfayqjshsf == 1 || from.ZmPcBase.Fwyfwdddzxccdsssfayqjshsf == 0 || from.ZmPcBase.Fwyfwdddzxccdsssfayqjshsf == 2)
                    {
                        //如果等于1，描述不能为空
                        if (from.ZmPcBase.Fwyfwdddzxccdsssfayqjshsf == 0)
                        {
                            if (string.IsNullOrWhiteSpace(from.ZmPcBase.FwyfwdddzxccdsssfayqjshsfPhoto))
                            {
                                return new RespRet<int>(false, "服务于房屋的电动自行车充电设施未按要求建设和收费照片不能为空");
                            }
                            from.ZmPcYh.Pczt += 1;
                            //整改了也需要往数据库插数据，标记已整改
                            var ddcid = Guid.NewGuid().ToString();
                            list.Add(new ZmPcYhLogDxSqjz
                            {
                                Fwbh = from.ZmPcBase.Fwbh,
                                Id = ddcid,
                                YhlogId = from.ZmPcBase.Id, //这个需要确认  挂接base的
                                Jcly = user.RoleType,
                                CheckId = "fwyfwdddzxccdsssfayqjshsf",
                                CheckName = "服务于房屋的电动自行车充电设施未按要求建设和收费",
                                CheckSm = from.ZmPcBase.FwyfwdddzxccdsssfayqjshsfMsg,
                                CheckBy = userNumber,
                                CheckTime = DateTime.Now,
                                CheckZp = from.ZmPcBase.FwyfwdddzxccdsssfayqjshsfPhoto,
                                CreateOn = DateTime.Now,
                                ZgValue = from.ZmPcBase.FwyfwdddzxccdsssfayqjshsfZgqk == null ? 0 : from.ZmPcBase.FwyfwdddzxccdsssfayqjshsfZgqk,
                                Xzq = basemsg2.Xzq,
                                Xzqdm = basemsg2.Xzqdm,
                                Town = basemsg2.Town,
                                Towndm = basemsg2.Towndm,
                                Village = basemsg2.Village,
                                Villagedm = basemsg2.Villagedm,
                                CheckNickname = user.Nickname

                            });
                            //如果整改
                            if (from.ZmPcBase.FwyfwdddzxccdsssfayqjshsfZgqk == 1)
                            {
                                from.ZmPcYh.Pczt -= 1;
                                if (string.IsNullOrWhiteSpace(from.ZmPcBase.FwyfwdddzxccdsssfayqjshsfZgPhoto))
                                {
                                    return new RespRet<int>(false, "服务于房屋的电动自行车充电设施是否按要求建设和收费d的整改照片不能为空");
                                }
                                listson.Add(new ZmPcYhlogDxzgsonSqjz
                                {
                                    CheckId = "fwyfwdddzxccdsssfayqjshsf",
                                    CheckName = "服务于房屋的电动自行车充电设施未按要求建设和收费",
                                    CreateOn = DateTime.Now,
                                    Fwbh = basemsg2.Fwbh,
                                    Id = Guid.NewGuid().ToString(),
                                    YhlogDxId = ddcid,  //隐患的id
                                    ZgBy = basemsg2.Hzxm,
                                    Zglx = "2",
                                    ZgTime = DateTime.Now.ToString(),
                                    ZgZp = from.ZmPcBase.FwyfwdddzxccdsssfayqjshsfZgPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcBase.FwyfwdddzxccdsssfayqjshsfZgPhoto.Split("|")),
                                    Xzq = basemsg2.Xzq,
                                    Xzqdm = basemsg2.Xzqdm,
                                    Town = basemsg2.Town,
                                    Towndm = basemsg2.Towndm,
                                    Village = basemsg2.Village,
                                    Villagedm = basemsg2.Villagedm
                                });
                            }

                        }
                    }
                    else
                    {
                        return new RespRet<int>(false, "服务于房屋的电动自行车充电设施是否按要求建设和收费只能为1或0或2");
                    }


                }




                if (from.ZmPcYh != null)
                {

                    //参数验证
                    //电动自行车、电动平衡车及其蓄电池在室内及安全出口处停放、充电(1是0否)
                    if (from.ZmPcYh.UseElectricBicycle == 1 || from.ZmPcYh.UseElectricBicycle == 0)
                    {
                        //如果等于1，描述不能为空
                        if (from.ZmPcYh.UseElectricBicycle == 1)
                        {
                            if (string.IsNullOrWhiteSpace(from.ZmPcYh.UseElectricBicyclePhoto))
                            {
                                return new RespRet<int>(false, "电动自行车、电动平衡车及其蓄电池在室内及安全出口处停放、充电的照片不能为空");
                            }
                            from.ZmPcYh.Pczt += 1;
                            //整改了也需要往数据库插数据，标记已整改
                            var ddcid = Guid.NewGuid().ToString();
                            list.Add(new ZmPcYhLogDxSqjz
                            {
                                Fwbh = from.ZmPcYh.Fwbh,
                                Id = ddcid,
                                YhlogId = yhlog_id,
                                Jcly = user.RoleType,
                                CheckId = "use_electric_bicycle",
                                CheckName = "电动自行车、电动平衡车及其蓄电池在室内及安全出口处停放、充电",
                                CheckSm = from.ZmPcYh.UseElectricBicycleMsg,
                                CheckBy = userNumber,
                                CheckTime = DateTime.Now,
                                CheckZp = from.ZmPcYh.UseElectricBicyclePhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.UseElectricBicyclePhoto.Split("|")),
                                CreateOn = DateTime.Now,
                                ZgValue = from.ZmPcYh.UseElectricBicycleZgqk == null ? 0 : from.ZmPcYh.UseElectricBicycleZgqk,
                                Xzq = basemsg2.Xzq,
                                Xzqdm = basemsg2.Xzqdm,
                                Town = basemsg2.Town,
                                Towndm = basemsg2.Towndm,
                                Village = basemsg2.Village,
                                Villagedm = basemsg2.Villagedm,
                                CheckNickname = user.Nickname

                            });
                            //如果整改
                            if (from.ZmPcYh.UseElectricBicycleZgqk == 1)
                            {
                                from.ZmPcYh.Pczt -= 1;
                                if (string.IsNullOrWhiteSpace(from.ZmPcYh.UseElectricBicycleZgPhoto))
                                {
                                    return new RespRet<int>(false, "电动自行车、电动平衡车及其蓄电池在室内及安全出口处停放、充电的整改照片不能为空");
                                }
                                if (from.ZmPcYh.Zxqlddcsl <= 0)
                                {
                                    return new RespRet<int>(false, "自行清理电动车数量必须大于0");
                                }
                                listson.Add(new ZmPcYhlogDxzgsonSqjz
                                {
                                    CheckId = "use_electric_bicycle",
                                    CheckName = "电动自行车、电动平衡车及其蓄电池在室内及安全出口处停放、充电",
                                    CreateOn = DateTime.Now,
                                    Fwbh = basemsg2.Fwbh,
                                    Id = Guid.NewGuid().ToString(),
                                    YhlogDxId = ddcid,
                                    ZgBy = basemsg2.Hzxm,
                                    ZgDdcNum = from.ZmPcYh.Zxqlddcsl,
                                    Zglx = "2",
                                    ZgTime = DateTime.Now.ToString(),
                                    ZgZp = from.ZmPcYh.UseElectricBicycleZgPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.UseElectricBicycleZgPhoto.Split("|")),
                                    Xzq = basemsg2.Xzq,
                                    Xzqdm = basemsg2.Xzqdm,
                                    Town = basemsg2.Town,
                                    Towndm = basemsg2.Towndm,
                                    Village = basemsg2.Village,
                                    Villagedm = basemsg2.Villagedm
                                });
                            }

                        }
                    }
                    else
                    {
                        return new RespRet<int>(false, "电动自行车、电动平衡车及其蓄电池在室内及安全出口处停放、充电的值只能为1或0");
                    }
                    //参数验证
                    // 在公共区域、租住房间内、地下室使用瓶装液化石油气(1是0否)
                    if (from.ZmPcYh.UseBottledLiquefiedGas == 1 || from.ZmPcYh.UseBottledLiquefiedGas == 0)
                    {
                        //如果等于1，描述不能为空
                        if (from.ZmPcYh.UseBottledLiquefiedGas == 1)
                        {
                            if (string.IsNullOrWhiteSpace(from.ZmPcYh.UseBottledLiquefiedGasPhoto))
                            {
                                return new RespRet<int>(false, " 在公共区域、租住房间内、地下室使用瓶装液化石油气的照片不能为空");
                            }
                            from.ZmPcYh.Pczt += 1;
                            var czfwid = Guid.NewGuid().ToString();
                            list.Add(new ZmPcYhLogDxSqjz
                            {
                                Fwbh = from.ZmPcYh.Fwbh,
                                Id = czfwid,
                                YhlogId = yhlog_id,
                                Jcly = user.RoleType,
                                CheckId = "use_bottled_liquefied_gas",
                                CheckName = " 在公共区域、租住房间内、地下室使用瓶装液化石油气",
                                CheckSm = from.ZmPcYh.UseBottledLiquefiedGasMsg,
                                CheckBy = userNumber,
                                CheckTime = DateTime.Now,
                                CheckZp = from.ZmPcYh.UseBottledLiquefiedGasPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.UseBottledLiquefiedGasPhoto.Split("|")),
                                CreateOn = DateTime.Now,
                                ZgValue = from.ZmPcYh.UseElectricBicycleZgqk == null ? 0 : from.ZmPcYh.UseElectricBicycleZgqk,
                                Xzq = basemsg2.Xzq,
                                Xzqdm = basemsg2.Xzqdm,
                                Town = basemsg2.Town,
                                Towndm = basemsg2.Towndm,
                                Village = basemsg2.Village,
                                Villagedm = basemsg2.Villagedm,
                                CheckNickname = user.Nickname,
                            });
                            //如果整改
                            if (from.ZmPcYh.UseBottledLiquefiedGasZgqk == 1)
                            {
                                from.ZmPcYh.Pczt -= 1;
                                if (string.IsNullOrWhiteSpace(from.ZmPcYh.UseBottledLiquefiedGasZgPhoto))
                                {
                                    return new RespRet<int>(false, " 在公共区域、租住房间内、地下室使用瓶装液化石油气整改照片不能为空");
                                }
                                if (from.ZmPcYh.Zxqlyhsyqsl <= 0)
                                {
                                    return new RespRet<int>(false, "自行清理液化石油气数量必须大于0");
                                }
                                listson.Add(new ZmPcYhlogDxzgsonSqjz
                                {
                                    CheckId = "use_bottled_liquefied_gas",
                                    CheckName = " 在公共区域、租住房间内、地下室使用瓶装液化石油气",
                                    CreateOn = DateTime.Now,
                                    Fwbh = basemsg2.Fwbh,
                                    Id = Guid.NewGuid().ToString(),
                                    YhlogDxId = czfwid,
                                    ZgBy = basemsg2.Hzxm,
                                    ZgYhsyqNum = from.ZmPcYh.Zxqlyhsyqsl,
                                    Zglx = "2",
                                    ZgTime = DateTime.Now.ToString(),
                                    ZgZp = from.ZmPcYh.UseBottledLiquefiedGasZgPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.UseBottledLiquefiedGasZgPhoto.Split("|")),
                                    Xzq = basemsg2.Xzq,
                                    Xzqdm = basemsg2.Xzqdm,
                                    Town = basemsg2.Town,
                                    Towndm = basemsg2.Towndm,
                                    Village = basemsg2.Village,
                                    Villagedm = basemsg2.Villagedm
                                });
                            }
                        }
                    }
                    else
                    {
                        return new RespRet<int>(false, " 在公共区域、租住房间内、地下室使用瓶装液化石油气的值只能为1或0");
                    }
                    //参数验证
                    //疏散走道、楼梯间、安全出口处堆放物品影响人员疏散(1是0否)
                    if (from.ZmPcYh.UseStackedItems == 1 || from.ZmPcYh.UseStackedItems == 0)
                    {
                        //如果等于1，描述不能为空
                        if (from.ZmPcYh.UseStackedItems == 1)
                        {
                            if (string.IsNullOrWhiteSpace(from.ZmPcYh.UseStackedItemsPhoto))
                            {
                                return new RespRet<int>(false, "疏散走道、楼梯间、安全出口处堆放物品影响人员疏散的照片不能为空");
                            }
                            from.ZmPcYh.Pczt += 1;
                            var sszdid = Guid.NewGuid().ToString();
                            list.Add(new ZmPcYhLogDxSqjz
                            {
                                Fwbh = from.ZmPcYh.Fwbh,
                                Id = sszdid,
                                YhlogId = yhlog_id,
                                Jcly = user.RoleType,
                                CheckId = "use_stacked_items",
                                CheckName = "疏散走道、楼梯间、安全出口处堆放物品影响人员疏散",
                                CheckSm = from.ZmPcYh.UseStackedItemsMsg,
                                CheckBy = userNumber,
                                CheckTime = DateTime.Now,
                                CheckZp = from.ZmPcYh.UseStackedItemsPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.UseStackedItemsPhoto.Split("|")),
                                CreateOn = DateTime.Now,
                                ZgValue = from.ZmPcYh.UseElectricBicycleZgqk == null ? 0 : from.ZmPcYh.UseElectricBicycleZgqk,
                                Xzq = basemsg2.Xzq,
                                Xzqdm = basemsg2.Xzqdm,
                                Town = basemsg2.Town,
                                Towndm = basemsg2.Towndm,
                                Village = basemsg2.Village,
                                Villagedm = basemsg2.Villagedm,
                                CheckNickname = user.Nickname
                            });
                            //如果整改
                            if (from.ZmPcYh.UseStackedItemsZgqk == 1)
                            {
                                from.ZmPcYh.Pczt -= 1;
                                if (string.IsNullOrWhiteSpace(from.ZmPcYh.UseStackedItemsZgPhoto))
                                {
                                    return new RespRet<int>(false, "疏散走道、楼梯间、安全出口处堆放物品影响人员疏散整改照片不能为空");
                                }
                                listson.Add(new ZmPcYhlogDxzgsonSqjz
                                {
                                    CheckId = "use_stacked_items",
                                    CheckName = "疏散走道、楼梯间、安全出口处堆放物品影响人员疏散",
                                    CreateOn = DateTime.Now,
                                    Fwbh = basemsg2.Fwbh,
                                    Id = Guid.NewGuid().ToString(),
                                    YhlogDxId = sszdid,
                                    ZgBy = basemsg2.Hzxm,
                                    Zglx = "2",
                                    ZgTime = DateTime.Now.ToString(),
                                    ZgZp = from.ZmPcYh.UseStackedItemsZgPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.UseStackedItemsZgPhoto.Split("|")),
                                    Xzq = basemsg2.Xzq,
                                    Xzqdm = basemsg2.Xzqdm,
                                    Town = basemsg2.Town,
                                    Towndm = basemsg2.Towndm,
                                    Village = basemsg2.Village,
                                    Villagedm = basemsg2.Villagedm,
                                }); ;
                            }
                        }
                    }
                    else
                    {
                        return new RespRet<int>(false, "疏散走道、楼梯间、安全出口处堆放物品影响人员疏散的值只能为1或0");
                    }
                    //参数验证
                    //灭火器未保持完好有效(1是0否)
                    if (from.ZmPcYh.Mhqwbcwhyx == 1 || from.ZmPcYh.Mhqwbcwhyx == 0)
                    {
                        //如果等于1，描述不能为空
                        if (from.ZmPcYh.Mhqwbcwhyx == 1)
                        {
                            if (string.IsNullOrWhiteSpace(from.ZmPcYh.MhqwbcwhyxPhoto))
                            {
                                return new RespRet<int>(false, "灭火器未保持完好有效的照片不能为空");
                            }
                            from.ZmPcYh.Pczt += 1;
                            //if (string.IsNullOrWhiteSpace(from.MhqwbcwhyxMsg))
                            //{
                            //    return new RespRet<int>(false, "灭火器未保持完好有效的描述不能为空");
                            //}
                            var mhqid = Guid.NewGuid().ToString();
                            list.Add(new ZmPcYhLogDxSqjz
                            {
                                Fwbh = from.ZmPcYh.Fwbh,
                                Id = mhqid,
                                YhlogId = yhlog_id,
                                Jcly = user.RoleType,
                                CheckId = "mhqwbcwhyx",
                                CheckName = "灭火器未保持完好有效",
                                CheckSm = from.ZmPcYh.MhqwbcwhyxMsg,
                                CheckBy = userNumber,
                                CheckTime = DateTime.Now,
                                CheckZp = from.ZmPcYh.MhqwbcwhyxPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.MhqwbcwhyxPhoto.Split("|")),
                                CreateOn = DateTime.Now,
                                ZgValue = from.ZmPcYh.UseElectricBicycleZgqk == null ? 0 : from.ZmPcYh.UseElectricBicycleZgqk,
                                Xzq = basemsg2.Xzq,
                                Xzqdm = basemsg2.Xzqdm,
                                Town = basemsg2.Town,
                                Towndm = basemsg2.Towndm,
                                Village = basemsg2.Village,
                                Villagedm = basemsg2.Villagedm,
                                CheckNickname = user.Nickname
                            });
                            //如果整改
                            if (from.ZmPcYh.MhqwbcwhyxZgqk == 1)
                            {
                                from.ZmPcYh.Pczt -= 1;
                                if (string.IsNullOrWhiteSpace(from.ZmPcYh.MhqwbcwhyxZgPhoto))
                                {
                                    return new RespRet<int>(false, "灭火器未保持完好有效整改照片不能为空");
                                }
                                listson.Add(new ZmPcYhlogDxzgsonSqjz
                                {
                                    CheckId = "mhqwbcwhyx",
                                    CheckName = "灭火器未保持完好有效",
                                    CreateOn = DateTime.Now,
                                    Fwbh = basemsg2.Fwbh,
                                    Id = Guid.NewGuid().ToString(),
                                    YhlogDxId = mhqid,
                                    ZgBy = basemsg2.Hzxm,
                                    Zglx = "2",
                                    ZgTime = DateTime.Now.ToString(),
                                    ZgZp = from.ZmPcYh.MhqwbcwhyxZgPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.MhqwbcwhyxZgPhoto.Split("|")),
                                    Xzq = basemsg2.Xzq,
                                    Xzqdm = basemsg2.Xzqdm,
                                    Town = basemsg2.Town,
                                    Towndm = basemsg2.Towndm,
                                    Village = basemsg2.Village,
                                    Villagedm = basemsg2.Villagedm
                                }); ;
                            }
                        }
                    }
                    else
                    {
                        return new RespRet<int>(false, "灭火器未保持完好有效的值只能为1或0");
                    }
                    //参数验证
                    //私拉乱接电线（1是0否）
                    if (from.ZmPcYh.Slljdx == 1 || from.ZmPcYh.Slljdx == 0)
                    {
                        //如果等于1，描述不能为空
                        if (from.ZmPcYh.Slljdx == 1)
                        {
                            if (string.IsNullOrWhiteSpace(from.ZmPcYh.SlljdxPhoto))
                            {
                                return new RespRet<int>(false, "私拉乱接电线的照片不能为空");
                            }
                            from.ZmPcYh.Pczt += 1;
                            var slljdxid = Guid.NewGuid().ToString();
                            list.Add(new ZmPcYhLogDxSqjz
                            {
                                Fwbh = from.ZmPcYh.Fwbh,
                                Id = slljdxid,
                                YhlogId = yhlog_id,
                                Jcly = user.RoleType,
                                CheckId = "slljdx",
                                CheckName = "私拉乱接电线",
                                CheckSm = from.ZmPcYh.SlljdxMsg,
                                CheckBy = userNumber,
                                CheckTime = DateTime.Now,
                                CheckZp = from.ZmPcYh.SlljdxPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.SlljdxPhoto.Split("|")),
                                CreateOn = DateTime.Now,
                                ZgValue = from.ZmPcYh.UseElectricBicycleZgqk == null ? 0 : from.ZmPcYh.UseElectricBicycleZgqk,
                                Xzq = basemsg2.Xzq,
                                Xzqdm = basemsg2.Xzqdm,
                                Town = basemsg2.Town,
                                Towndm = basemsg2.Towndm,
                                Village = basemsg2.Village,
                                Villagedm = basemsg2.Villagedm,
                                CheckNickname = user.Nickname
                            });
                            //如果整改
                            if (from.ZmPcYh.SlljdxZgqk == 1)
                            {
                                from.ZmPcYh.Pczt -= 1;
                                if (string.IsNullOrWhiteSpace(from.ZmPcYh.SlljdxZgPhoto))
                                {
                                    return new RespRet<int>(false, "私拉乱接电线整改照片不能为空");
                                }
                                listson.Add(new ZmPcYhlogDxzgsonSqjz
                                {
                                    CheckId = "slljdx",
                                    CheckName = "私拉乱接电线",
                                    CreateOn = DateTime.Now,
                                    Fwbh = basemsg2.Fwbh,
                                    Id = Guid.NewGuid().ToString(),
                                    YhlogDxId = slljdxid,
                                    ZgBy = basemsg2.Hzxm,
                                    Zglx = "2",
                                    ZgTime = DateTime.Now.ToString(),
                                    ZgZp = from.ZmPcYh.SlljdxZgPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.SlljdxZgPhoto.Split("|")),
                                    Xzq = basemsg2.Xzq,
                                    Xzqdm = basemsg2.Xzqdm,
                                    Town = basemsg2.Town,
                                    Towndm = basemsg2.Towndm,
                                    Village = basemsg2.Village,
                                    Villagedm = basemsg2.Villagedm
                                }); ;
                            }
                        }
                    }
                    else
                    {
                        return new RespRet<int>(false, "私拉乱接电线的值只能为1或0");
                    }
                    //参数验证
                    //简易喷淋灭火系统未保持完好有效(1是0否2不涉及)
                    if (from.ZmPcYh.Jyplmhxtwbcwhyx == 1 || from.ZmPcYh.Jyplmhxtwbcwhyx == 0 || from.ZmPcYh.Jyplmhxtwbcwhyx == 2)
                    {
                        if (from.ZmPcYh.Jyplmhxtwbcwhyx == 2)
                        {
                        }
                        else
                        {
                            //如果等于1，描述不能为空
                            if (from.ZmPcYh.Jyplmhxtwbcwhyx == 1)
                            {
                                if (string.IsNullOrWhiteSpace(from.ZmPcYh.JyplmhxtwbcwhyxPhoto))
                                {
                                    return new RespRet<int>(false, "简易喷淋灭火系统未保持完好有效的照片不能为空");
                                }
                                from.ZmPcYh.Pczt += 1;

                                var jyplhid = Guid.NewGuid().ToString();
                                list.Add(new ZmPcYhLogDxSqjz
                                {
                                    Fwbh = from.ZmPcYh.Fwbh,
                                    Id = jyplhid,
                                    YhlogId = yhlog_id,
                                    Jcly = user.RoleType,
                                    CheckId = "jyplmhxtwbcwhyx",
                                    CheckName = "简易喷淋灭火系统未保持完好有效",
                                    CheckSm = from.ZmPcYh.JyplmhxtwbcwhyxMsg,
                                    CheckBy = userNumber,
                                    CheckTime = DateTime.Now,
                                    CheckZp = from.ZmPcYh.JyplmhxtwbcwhyxPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.JyplmhxtwbcwhyxPhoto.Split("|")),
                                    CreateOn = DateTime.Now,
                                    ZgValue = from.ZmPcYh.UseElectricBicycleZgqk == null ? 0 : from.ZmPcYh.UseElectricBicycleZgqk,
                                    Xzq = basemsg2.Xzq,
                                    Xzqdm = basemsg2.Xzqdm,
                                    Town = basemsg2.Town,
                                    Towndm = basemsg2.Towndm,
                                    Village = basemsg2.Village,
                                    Villagedm = basemsg2.Villagedm,
                                    CheckNickname = user.Nickname
                                });
                                //如果整改
                                if (from.ZmPcYh.JyplmhxtwbcwhyxZgqk == 1)
                                {
                                    from.ZmPcYh.Pczt -= 1;
                                    if (string.IsNullOrWhiteSpace(from.ZmPcYh.JyplmhxtwbcwhyxZgPhoto))
                                    {
                                        return new RespRet<int>(false, "简易喷淋灭火系统未保持完好有效整改照片不能为空");
                                    }
                                    listson.Add(new ZmPcYhlogDxzgsonSqjz
                                    {
                                        CheckId = "jyplmhxtwbcwhyx",
                                        CheckName = "简易喷淋灭火系统未保持完好有效",
                                        CreateOn = DateTime.Now,
                                        Fwbh = basemsg2.Fwbh,
                                        Id = Guid.NewGuid().ToString(),
                                        YhlogDxId = jyplhid,
                                        ZgBy = basemsg2.Hzxm,
                                        Zglx = "2",
                                        ZgTime = DateTime.Now.ToString(),
                                        ZgZp = from.ZmPcYh.JyplmhxtwbcwhyxZgPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.JyplmhxtwbcwhyxZgPhoto.Split("|")),
                                        Xzq = basemsg2.Xzq,
                                        Xzqdm = basemsg2.Xzqdm,
                                        Town = basemsg2.Town,
                                        Towndm = basemsg2.Towndm,
                                        Village = basemsg2.Village,
                                        Villagedm = basemsg2.Villagedm
                                    }); ;
                                }
                            }
                        }
                    }
                    else
                    {
                        return new RespRet<int>(false, "简易喷淋灭火系统未保持完好有效的值只能为1、0、2");
                    }

                    //参数验证
                    //烟感报警器未保持完好有效(1是0否2不涉及)
                    if (from.ZmPcYh.Ygbjwfwhyx == 1 || from.ZmPcYh.Ygbjwfwhyx == 0 || from.ZmPcYh.Ygbjwfwhyx == 2)
                    {
                        if (from.ZmPcYh.Ygbjwfwhyx == 2)
                        {
                        }
                        else
                        {
                            //如果等于1，描述不能为空
                            if (from.ZmPcYh.Ygbjwfwhyx == 1)
                            {
                                if (string.IsNullOrWhiteSpace(from.ZmPcYh.YgbjwfwhyxPhoto))
                                {
                                    return new RespRet<int>(false, "烟感报警器未保持完好有效的照片不能为空");
                                }
                                from.ZmPcYh.Pczt += 1;
                                var ygbjid = Guid.NewGuid().ToString();
                                list.Add(new ZmPcYhLogDxSqjz
                                {
                                    Fwbh = from.ZmPcYh.Fwbh,
                                    Id = ygbjid,
                                    YhlogId = yhlog_id,
                                    Jcly = user.RoleType,
                                    CheckId = "ygbjwfwhyx",
                                    CheckName = "烟感报警器未保持完好有效",
                                    CheckSm = from.ZmPcYh.YgbjwfwhyxMsg,
                                    CheckBy = userNumber,
                                    CheckTime = DateTime.Now,
                                    CheckZp = from.ZmPcYh.YgbjwfwhyxPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.YgbjwfwhyxPhoto.Split("|")),
                                    CreateOn = DateTime.Now,
                                    ZgValue = from.ZmPcYh.UseElectricBicycleZgqk == null ? 0 : from.ZmPcYh.UseElectricBicycleZgqk,
                                    Xzq = basemsg2.Xzq,
                                    Xzqdm = basemsg2.Xzqdm,
                                    Town = basemsg2.Town,
                                    Towndm = basemsg2.Towndm,
                                    Village = basemsg2.Village,
                                    Villagedm = basemsg2.Villagedm,
                                    CheckNickname = user.Nickname
                                });
                                //如果整改
                                if (from.ZmPcYh.YgbjwfwhyxMsgZgqk == 1)
                                {
                                    from.ZmPcYh.Pczt -= 1;
                                    if (string.IsNullOrWhiteSpace(from.ZmPcYh.YgbjwfwhyxMsgZgPhoto))
                                    {
                                        return new RespRet<int>(false, "烟感报警器未保持完好有效整改照片不能为空");
                                    }
                                    listson.Add(new ZmPcYhlogDxzgsonSqjz
                                    {
                                        CheckId = "ygbjwfwhyx",
                                        CheckName = "烟感报警器未保持完好有效",
                                        CreateOn = DateTime.Now,
                                        Fwbh = basemsg2.Fwbh,
                                        Id = Guid.NewGuid().ToString(),
                                        YhlogDxId = ygbjid,
                                        ZgBy = basemsg2.Hzxm,
                                        Zglx = "2",
                                        ZgTime = DateTime.Now.ToString(),
                                        ZgZp = from.ZmPcYh.YgbjwfwhyxMsgZgPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.YgbjwfwhyxMsgZgPhoto.Split("|")),
                                        Xzq = basemsg2.Xzq,
                                        Xzqdm = basemsg2.Xzqdm,
                                        Town = basemsg2.Town,
                                        Towndm = basemsg2.Towndm,
                                        Village = basemsg2.Village,
                                        Villagedm = basemsg2.Villagedm
                                    }); ;
                                }
                            }
                        }
                    }
                    else
                    {
                        return new RespRet<int>(false, "烟感报警器未保持完好有效的值只能为1、0、2");
                    }

                    //参数验证
                    //是否存在窗口、防护网、广告牌、铁栅栏（1是0否）
                    if (from.ZmPcYh.Sfczckfhwggptzl == 1 || from.ZmPcYh.Sfczckfhwggptzl == 0)
                    {
                        //如果等于1，描述不能为空
                        if (from.ZmPcYh.Sfczckfhwggptzl == 1)
                        {
                            if (string.IsNullOrWhiteSpace(from.ZmPcYh.SfczckfhwggptzlPhoto))
                            {
                                return new RespRet<int>(false, "存在窗口、防护网、广告牌、铁栅栏的照片不能为空");
                            }
                            from.ZmPcYh.Pczt += 1;
                            //if (string.IsNullOrWhiteSpace(from.SlljdxMsg))
                            //{
                            //    return new RespRet<int>(false, "私拉乱接电线的描述不能为空");
                            //}
                            var slljdxid = Guid.NewGuid().ToString();
                            list.Add(new ZmPcYhLogDxSqjz
                            {
                                Fwbh = from.ZmPcYh.Fwbh,
                                Id = slljdxid,
                                YhlogId = yhlog_id,
                                Jcly = user.RoleType,
                                CheckId = "sfczckfhwggptzl",
                                CheckName = "是否存在窗口、防护网、广告牌、铁栅栏",
                                CheckSm = from.ZmPcYh.SfczckfhwggptzlMsg,
                                CheckBy = userNumber,
                                CheckTime = DateTime.Now,
                                CheckZp = from.ZmPcYh.SfczckfhwggptzlPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.SfczckfhwggptzlPhoto.Split("|")),
                                CreateOn = DateTime.Now,
                                ZgValue = from.ZmPcYh.SfczckfhwggptzlZgqk == null ? 0 : from.ZmPcYh.SfczckfhwggptzlZgqk,
                                Xzq = basemsg2.Xzq,
                                Xzqdm = basemsg2.Xzqdm,
                                Town = basemsg2.Town,
                                Towndm = basemsg2.Towndm,
                                Village = basemsg2.Village,
                                Villagedm = basemsg2.Villagedm,
                                CheckNickname = user.Nickname
                            });
                            //如果整改
                            if (from.ZmPcYh.SfczckfhwggptzlZgqk == 1)
                            {
                                from.ZmPcYh.Pczt -= 1;
                                if (string.IsNullOrWhiteSpace(from.ZmPcYh.SfczckfhwggptzlZgPhoto))
                                {
                                    return new RespRet<int>(false, "私拉乱接电线整改照片不能为空");
                                }
                                listson.Add(new ZmPcYhlogDxzgsonSqjz
                                {
                                    CheckId = "sfczckfhwggptzl",
                                    CheckName = "是否存在窗口、防护网、广告牌、铁栅栏",
                                    CreateOn = DateTime.Now,
                                    Fwbh = basemsg2.Fwbh,
                                    Id = Guid.NewGuid().ToString(),
                                    YhlogDxId = slljdxid,
                                    ZgBy = basemsg2.Hzxm,
                                    Zglx = "2",
                                    ZgTime = DateTime.Now.ToString(),
                                    ZgZp = from.ZmPcYh.SfczckfhwggptzlZgPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.SfczckfhwggptzlZgPhoto.Split("|")),
                                    Xzq = basemsg2.Xzq,
                                    Xzqdm = basemsg2.Xzqdm,
                                    Town = basemsg2.Town,
                                    Towndm = basemsg2.Towndm,
                                    Village = basemsg2.Village,
                                    Villagedm = basemsg2.Villagedm
                                }); ;
                            }
                        }
                    }
                    else
                    {
                        return new RespRet<int>(false, "是否存在窗口、防护网、广告牌、铁栅栏的值只能为1或0");
                    }
                    if (string.IsNullOrWhiteSpace(from.ZmPcYh.Sign))
                    {
                        return new RespRet<int>(false, "签字信息不能为空");
                    }

                }

                
                if (flag && user.RoleType == 2)   //在抽检任务中且为市级
                {
                    if (taskcj!=null&& taskcj.Hyzt == 1)  //已经核验过 
                    {
                        //查到结果
                        var pc2 = _dbContext.ZmPcBaseLogSqjz.AsNoTracking().FirstOrDefault(u => u.Fwbh == from.ZmPcBase.Fwbh && u.Yhly == 2 && u.iscj == 1 && u.Id == taskcj.baseid);//查到抽检的信息
                        if (pc2 != null && pc2.Jsrysstd == "否" && taskcj.Pch != "第一轮") //结果为 当前轮次 可修改
                        {
                            DateTime endofday = pc2.CreateOn.Date.AddDays(1).AddSeconds(-1);//上次存储的时间
                            if (from.ZmPcBase.CreateOn < endofday)
                            {

                            }
                            else
                            {
                                var r1 = new RespRet<int>(false, "市级核验抽检已为不合格且不在修改时间段内，不可再核验");
                                WriteSystemLog("housessqjz/update-yhzc", r1, from);
                                return r1;
                            }
                        }
                    }
                }
                //操作数据库信息
                using (var transaction = _dbContext.Database.BeginTransaction())
                {
                    try
                    {
                        //最新只有区级角色才可修改房屋状态
                        if (user.RoleType == 3 )
                        {
                            if (taskcj != null && taskcj.Hyzt == 1)
                            {
                                var pc2 = _dbContext.ZmPcBaseLogSqjz.AsNoTracking().FirstOrDefault(u => u.Fwbh == from.ZmPcBase.Fwbh && u.Yhly == 2 && u.iscj == 1 && u.Id == taskcj.baseid);//查到抽检的信息
                                if (pc2 != null && pc2.Jsrysstd == "否" && (from.ZmPcBase.Fwzt == 2 || from.ZmPcBase.Fwzt == 1) && taskcj.Pch != "第一轮") //第一轮可修改
                                {
                                    var r1 = new RespRet<int>(false, "市级核验为不合格的，不可再更改其房屋状态");
                                    WriteSystemLog("housessqjz/update-yhzc", r1, from);
                                    return r1;
                                }
                            }
                            //更新房屋状态表的状态
                            // 单行获取当天最后一刻并格式化
                            string time = DateTime.Today
                                .AddHours(23)
                                .AddMinutes(59)
                                .AddSeconds(59)
                                .ToString("yyyy-MM-dd HH:mm:ss");
                            string table_name = "zm_building_fwzt_" + DateTime.Now.Year;
                            var fwzt_log = _dbContext.Database.GetDbConnection().Query<ZmBuildingFwzt>($" select *From {table_name} where fwbh=@fwbh and final_create_on=@time  ", new { @fwbh = from.ZmPcBase.Fwbh, @time = time }).FirstOrDefault();
                            //如果没有记录，则应抛出异常
                            if (fwzt_log == null)
                            {
                                string insertsql = $" insert into {table_name} (fwbh,xzqdm,final_create_on,final_fwzt,towndm,villagedm) values (@fwbh,@xzqdm,@final_create_on,@fwzt,@towndm,@villagedm) ";
                                _dbContext.Database.GetDbConnection().Execute(insertsql, new { @fwbh = from.ZmPcBase.Fwbh, @final_create_on = time, @xzqdm = basemsg2.Xzqdm, @towndm = basemsg2.Towndm, @villagedm = basemsg2.Villagedm, @fwzt = from.ZmPcBase.Fwzt });
                            }
                            //找到记录，用当前村级状态与街镇最新状态判断出 最新的房屋状态，进行更新
                            else
                            {
                                if (from.ZmPcBase.Fwzt != null)
                                {
                                    string update_sql = $" update {table_name} set final_fwzt=@fwzt where fwbh=@fwbh and final_create_on=@time  ";
                                    _dbContext.Database.GetDbConnection().Execute(update_sql, new { @fwbh = from.ZmPcBase.Fwbh, @time = time, @fwzt = from.ZmPcBase.Fwzt });
                                }
                            }

                            var zc_detailebyfwbh = _dbContext.ZmTaskDetail.FirstOrDefault(c => c.Fwbh == from.ZmPcBase.Fwbh);
                            //在任务列表中 且    设置了不出租和已拆除   直接在任务列表删除                                                                       
                            if (zc_detailebyfwbh != null && from.ZmPcBase.Fwzt != null)
                            {
                                string delete_sql = $" delete from  zm_taskdetail  where fwbh=@fwbh ";
                                _dbContext.Database.GetDbConnection().Execute(delete_sql, new { @fwbh = from.ZmPcBase.Fwbh });
                            }
                        }
                        

                        if (pc != null)
                        {
                            _dbContext.Remove(pc);
                            if (_dbContext.SaveChanges() == 0)
                            {
                                var r1 = new RespRet<int>(false, "操作失败");
                                WriteSystemLog("housessqjz/update-yhzc", r1, from);
                                return r1;
                            }
                            if (basemsg2.CreateOn >= Convert.ToDateTime("2024-04-01"))
                            {
                            }
                            else
                            {
                                if (DateTime.Now.Date >= Convert.ToDateTime("2024-04-01"))
                                {
                                    from.ZmPcBase.Ckfhwggptzlsl = pc.Ckfhwggptzlsl;
                                }
                            }
                        }
                        else
                        {
                            if (basemsg2.CreateOn >= Convert.ToDateTime("2024-04-01"))
                            {
                            }
                            else
                            {
                                if (DateTime.Now.Date >= Convert.ToDateTime("2024-04-01"))
                                {
                                    from.ZmPcBase.Ckfhwggptzlsl = 0;
                                }
                            }
                        }
                        if (from.ZmPcBase.Fwzt == 1 || from.ZmPcBase.Fwzt == 2)
                        {
                            if (pc != null)
                            {
                                int? fwzt = from.ZmPcBase.Fwzt;
                                from.ZmPcBase = pc;
                                from.ZmPcBase.Id = id;
                                from.ZmPcBase.Fwzt = fwzt;
                            }
                        }
                        if (from.ZmPcBase.Jsrysstd != "是" && from.ZmPcBase.Jsrysstd != "否")
                        {
                            from.ZmPcBase.Jsrysstd = null;
                        }
                        _dbContext.Add(from.ZmPcBase);
                        int i = _dbContext.SaveChanges();
                        if (i > 0)
                        {
                            ZmPcBaseLogSqjz baselog = _mapper.Map<ZmPcBaseLogSqjz>(from.ZmPcBase);
                            baselog.Sfyzc = "是";
                            _dbContext.Add(baselog);
                            var res = _dbContext.SaveChanges();
                            if (res > 0)
                            {
                                //抽检任务部分
                                if (from.ZmPcBase.iscj == 1)
                                {
                                    var detaile = _dbContext.ZmTaskDetail.FirstOrDefault(c => c.Id == from.ZmPcBase.DetaileId);
                                    if (detaile == null)
                                    {
                                        transaction.Rollback();
                                        var rerr = new RespRet<int>(false, "操作失败");
                                        WriteSystemLog("housessqjz/update-yhzc", rerr, from);
                                        return rerr;
                                    }
                                    if (detaile.Hyzt == 1)
                                    {
                                        detaile.baseid = from.ZmPcBase.Id;
                                        _dbContext.SaveChanges();
                                    }
                                    else
                                    {
                                        detaile.Hyzt = 1;
                                        detaile.baseid = from.ZmPcBase.Id;

                                        if (_dbContext.SaveChanges() == 0)
                                        {
                                            transaction.Rollback();
                                            var rerr = new RespRet<int>(false, "操作失败");
                                            WriteSystemLog("housessqjz/update-yhzc", rerr, from);
                                            return rerr;
                                        }
                                    }
                                }

                                if (from.ZmPcBase.Fwzt == 1 || from.ZmPcBase.Fwzt == 2)
                                {
                                    var relist = _dbContext.ZmPcYhSqjz.Where(c => c.Fwbh == from.ZmPcBase.Fwbh && c.Jcly == user.RoleType).ToList();
                                    if (relist != null && relist.Count > 0)
                                    {
                                        _dbContext.RemoveRange(relist);
                                        if (_dbContext.SaveChanges() > 0)
                                        {
                                        }
                                        else
                                        {
                                            transaction.Rollback();
                                            var rerr = new RespRet<int>(false, "操作失败", i);
                                            WriteSystemLog("housessqjz/update-yhzc", rerr, from);
                                            return rerr;
                                        }
                                    }

                                    ZmPcYhSqjz addcj2 = new ZmPcYhSqjz
                                    {
                                        BaseId = id,
                                        Id = Guid.NewGuid().ToString(),
                                        CreateBy = user.Number,
                                        CreateOn = DateTime.Now,
                                        CreateIp = this.IpAddress(),
                                        Fwbh = from.ZmPcBase.Fwbh,
                                        Jcly = user.RoleType,
                                        Pcsj = DateTime.Now,
                                        Pczt = 1,
                                        Xzqdm = basemsg2.Xzqdm,
                                        Town = basemsg2.Town,
                                        Village = basemsg2.Village,
                                        Xzq = basemsg2.Xzq,
                                        Towndm = basemsg2.Towndm,
                                        Villagedm = basemsg2.Villagedm
                                    };
                                    ZmPcYhLogSqjz addlogcj2 = _mapper.Map<ZmPcYhLogSqjz>(addcj2);
                                    _dbContext.Add(addcj2);
                                    _dbContext.Add(addlogcj2);
                                    if (_dbContext.SaveChanges() == 2)
                                    {
                                        transaction.Commit();
                                        return new RespRet<int>(true, "操作成功", i);
                                    }
                                    else
                                    {
                                        transaction.Rollback();
                                        var rerr = new RespRet<int>(false, "操作失败", i);
                                        WriteSystemLog("housessqjz/update-yhzc", rerr, from);
                                        return rerr;
                                    }
                                }
                            }
                            //隐患部分操作数据库
                            if (from.ZmPcYh == null)
                            {
                                transaction.Commit();
                                return new RespRet<int>(true, "操作成功", i);
                            }

                            var basemsg = _dbContext.ZmPcYhSqjz.AsNoTracking().FirstOrDefault(u => u.Fwbh == from.ZmPcYh.Fwbh && u.Jcly == user.RoleType && u.IsDelete != 1);
                            if (basemsg != null)
                            {
                                _dbContext.Remove(basemsg);
                                int remove_res = _dbContext.SaveChanges();
                                if (remove_res == 0)
                                {
                                    return new RespRet<int>(false, "操作失败");
                                }
                            }
                            //之前没有采集过，设置默认信息
                            from.ZmPcYh.CreateBy = userNumber;
                            from.ZmPcYh.CreateOn = DateTime.Now;
                            from.ZmPcYh.CreateIp = this.IpAddress();
                            from.ZmPcYh.IsDelete = null;
                            from.ZmPcYh.DeleteBy = null;
                            from.ZmPcYh.DeleteOn = null;
                            from.ZmPcYh.DeleteIp = null;
                            from.ZmPcYh.Id = yhlog_id;
                            from.ZmPcYh.Fwbh = from.ZmPcYh.Fwbh;
                            from.ZmPcYh.Xzq = basemsg2.Xzq;
                            from.ZmPcYh.Xzqdm = basemsg2.Xzqdm;
                            from.ZmPcYh.Town = basemsg2.Town;
                            from.ZmPcYh.Towndm = basemsg2.Towndm;
                            from.ZmPcYh.Village = basemsg2.Village;
                            from.ZmPcYh.Villagedm = basemsg2.Villagedm;
                            from.ZmPcYh.Jcly = user.RoleType;
                            if (from.ZmPcYh.Pczt > 0)
                            {
                                from.ZmPcYh.Pczt = 2;
                            }
                            else
                            {
                                from.ZmPcYh.Pczt = 1;
                            }
                            //查询出base表的记录
                            var base1 = _dbContext.ZmPcBaseSqjz.AsNoTracking().FirstOrDefault(u => u.Fwbh == from.ZmPcYh.Fwbh && u.Yhly == user.RoleType && u.IsDelete != 1);
                            if (base1 != null)
                            {

                                //通过双通道的值，判断是否需要加入隐患
                                #region
                                //if (base1.Jsrysstd == "否")
                                //{
                                //    var rysstdid = Guid.NewGuid().ToString();
                                //    list.Add(new ZmPcYhLogDxSqjz
                                //    {
                                //        Fwbh = from.Fwbh,
                                //        Id = rysstdid,
                                //        YhlogId = yhlog_id,
                                //        Jcly = zmUser.RoleType,
                                //        CheckId = "wabzjsrysstd",
                                //        CheckName = "未按照标准建设疏散通道",
                                //        CheckSm = "未按照标准建设疏散通道",
                                //        CheckBy = userNumber,
                                //        CheckTime = DateTime.Now,
                         
                                //        CreateOn = DateTime.Now,
                                //        ZgValue = 0,
                                //        Xzq = user.Xzq,
                                //        Xzqdm = user.Xzqdm,
                                //        Town = user.Town,
                                //        Towndm = user.Towndm,
                                //        Village = user.Village,
                                //        Villagedm = user.Villagedm,
                                //        CheckNickname = zmUser.Nickname
                                //    });
                                //}
                                #endregion
                                from.ZmPcYh.Pcsj = base1.Pcsj;
                                from.ZmPcYh.BaseId = base1.Id;
                            }
                            else
                            {
                                transaction.Rollback();
                                return new RespRet<int>(false, "请先进行房屋基础信息采集", 0);
                            }
                            from.ZmPcYh.UseElectricBicyclePhoto = from.ZmPcYh.UseElectricBicyclePhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.UseElectricBicyclePhoto.Split("|"));
                            from.ZmPcYh.UseBottledLiquefiedGasPhoto = from.ZmPcYh.UseBottledLiquefiedGasPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.UseBottledLiquefiedGasPhoto.Split("|"));
                            from.ZmPcYh.UseStackedItemsPhoto = from.ZmPcYh.UseStackedItemsPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.UseStackedItemsPhoto.Split("|"));
                            from.ZmPcYh.SlljdxPhoto = from.ZmPcYh.SlljdxPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.SlljdxPhoto.Split("|"));
                            from.ZmPcYh.YgbjwfwhyxPhoto = from.ZmPcYh.YgbjwfwhyxPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.YgbjwfwhyxPhoto.Split("|"));
                            from.ZmPcYh.MhqwbcwhyxPhoto = from.ZmPcYh.MhqwbcwhyxPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.MhqwbcwhyxPhoto.Split("|"));
                            from.ZmPcYh.JyplmhxtwbcwhyxPhoto = from.ZmPcYh.JyplmhxtwbcwhyxPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.JyplmhxtwbcwhyxPhoto.Split("|"));
                            from.ZmPcYh.UseElectricBicycleZgPhoto = from.ZmPcYh.UseElectricBicycleZgPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.UseElectricBicycleZgPhoto.Split("|"));
                            from.ZmPcYh.UseBottledLiquefiedGasZgPhoto = from.ZmPcYh.UseBottledLiquefiedGasZgPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.UseBottledLiquefiedGasZgPhoto.Split("|"));
                            from.ZmPcYh.UseStackedItemsZgPhoto = from.ZmPcYh.UseStackedItemsZgPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.UseStackedItemsZgPhoto.Split("|"));
                            from.ZmPcYh.SlljdxZgPhoto = from.ZmPcYh.SlljdxZgPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.SlljdxZgPhoto.Split("|"));
                            from.ZmPcYh.YgbjwfwhyxMsgZgPhoto = from.ZmPcYh.YgbjwfwhyxMsgZgPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.YgbjwfwhyxMsgZgPhoto.Split("|"));
                            from.ZmPcYh.MhqwbcwhyxZgPhoto = from.ZmPcYh.MhqwbcwhyxZgPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.MhqwbcwhyxZgPhoto.Split("|"));
                            from.ZmPcYh.JyplmhxtwbcwhyxZgPhoto = from.ZmPcYh.JyplmhxtwbcwhyxZgPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.JyplmhxtwbcwhyxZgPhoto.Split("|"));
                            from.ZmPcYh.SfczckfhwggptzlPhoto = from.ZmPcYh.SfczckfhwggptzlPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.SfczckfhwggptzlPhoto.Split("|"));
                            from.ZmPcYh.SfczckfhwggptzlZgPhoto = from.ZmPcYh.SfczckfhwggptzlZgPhoto == null ? null : JsonConvert.SerializeObject(from.ZmPcYh.SfczckfhwggptzlZgPhoto.Split("|"));

                            _dbContext.Add(from.ZmPcYh);
                            int removeres = _dbContext.SaveChanges();
                            if (removeres > 0)
                            {
                                if (list != null && list.Count() > 0)
                                {
                                    _dbContext.AddRange(list);
                                    if (_dbContext.SaveChanges() != list.Count())
                                    {
                                        transaction.Rollback();
                                        return new RespRet<int>(false, "操作失败", 0);
                                    }
                                }
                                if (listson != null && listson.Count() > 0)
                                {
                                    _dbContext.AddRange(listson);
                                    if (_dbContext.SaveChanges() != listson.Count())
                                    {
                                        transaction.Rollback();
                                        return new RespRet<int>(false, "操作失败", 0);
                                    }
                                }
                                ZmPcYhLogSqjz baselogsqjz = _mapper.Map<ZmPcYhLogSqjz>(from.ZmPcYh);
                                baselogsqjz.Id = yhlog_id;
                                _dbContext.Add(baselogsqjz);
                                if (_dbContext.SaveChanges() > 0)
                                {
                                    transaction.Commit();
                                    return new RespRet<int>(true, "操作成功", i);
                                }
                            }
                            transaction.Rollback();
                            return new RespRet<int>(false, "操作失败", 0);

                        }
                        transaction.Rollback();
                        var r = new RespRet<int>(false, "操作失败", i);
                        WriteSystemLog("housessqjz/update-yhzc", r, from);
                        return r;
                    }
                    catch (Exception ex)
                    {
                        // 回滚事务
                        transaction.Rollback();
                        var res = new RespRet<int>(false, ex.ToString());
                        WriteSystemLogError("housessqjz/update-yhzc", res, from);
                        res.Msg = "系统异常";
                        return res;
                    }
                }
            }
            catch (Exception ex)
            {
                var res = new RespRet<int>(false, ex.ToString());
                WriteSystemLogError("housessqjz/update-yhzc", res, from);
                res.Msg = "系统异常";
                return res;
            }
        }












        /// <summary>
        /// 修改用户姓名
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <returns>请求token</returns>
        //[AllowAnonymous]
        [HttpPost("housessqjz/updateusername")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<int>), 200)]
        public RespRet<int> UpdateUserName([FromQuery] string name)
        {
            try
            {
                var userNumber = this.CurrentUser();
                if (string.IsNullOrEmpty(userNumber))
                {
                    return new RespRet<int>(false, "user not logined");
                }
                if (string.IsNullOrWhiteSpace(name))
                {
                    return new RespRet<int>(false, "用户姓名不能为空");
                }
                var user = _userRepository.FirstOrDefault(c => c.Number == userNumber && c.Disabled != 1);
                if (user == null)
                {
                    var res = new RespRet<int>(false, "未找到用户,请登录后重试");
                    WriteSystemLog("housessqjz/updatename", res, new { userNumber = userNumber, name = name });
                }
                user.Nickname = name;
                _dbContext.Update(user);
                int i = _dbContext.SaveChanges();
                if (i > 0)
                {
                    var res = new RespRet<int>(true, "修改成功", i);
                    WriteSystemLog("housessqjz/updatename", res, new { userNumber = userNumber, name = name });
                    return res;
                }
                else
                {
                    var res = new RespRet<int>(false, "修改失败", i);
                    WriteSystemLog("housessqjz/updatename", res, new { userNumber = userNumber, name = name });
                    return res;
                }
            }
            catch (Exception ex)
            {
                var res = new RespRet<int>(false, ex.ToString());
                WriteSystemLogError("login/confirm", res, name);
                res.Msg = "修改失败";
                return res;
            }
        }


        /// <summary>
        /// 获取隐患整改详情
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("housessqjz/search-gjzz")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<ZmPcGjzzCj>), 200)]
        public RespRet<ZmPcGjzzCj> Yhxq2([FromQuery] string villagedm)
        {
            var userNumber = this.CurrentUser();
            try
            {
                if (string.IsNullOrEmpty(userNumber))
                {
                    return new RespRet<ZmPcGjzzCj>(false, "user not logined");
                }
                if (string.IsNullOrEmpty(villagedm))
                {
                    return new RespRet<ZmPcGjzzCj>(false, "村代码不能为空");
                }
                var from = _dbContext.ZmPcGjzzCj.FirstOrDefault(c => c.Villagedm == villagedm);
                if (from == null)
                {
                    from = new ZmPcGjzzCj();
                }
                from.Fj = from.Fj == null ? null : string.Join("|", JsonStr2List(from.Fj));
                //获取统计信息
                string sql = @"select 1 id, mzltlj,zzfasl,zzsgsl,
case when qcddzxcsl is null then 0 else qcddzxcsl end qcddzxcsl,
case when sjjzrksl is null then 0 else sjjzrksl end sjjzrksl,
case when azgdjsbpsl is null then 0 else azgdjsbpsl end azgdjsbpsl,
case when qlddzxcsl is null then 0 else qlddzxcsl end qlddzxcsl,
case when qlyhsyqpsl is null then 0 else qlyhsyqpsl end qlyhsyqpsl
from (select count(case when jzxyssltsl>=2 then 1 end) mzltlj,
count(case when sstdjsqk='正在制定方案' then 1 end) zzfasl,
count(case when sstdjsqk='正在施工改造' then 1 end)zzsgsl,
sum(bdfwjzrydddzxcsl)  qcddzxcsl,
sum(jzrks) sjjzrksl,
sum(xggdjsbp) azgdjsbpsl
from zm_pc_base where village=@villagedm) a,
(select sum(zxqlddcsl)qlddzxcsl,sum(zxqlyhsyqsl) qlyhsyqpsl  from zm_pc_yhlog a left join zm_buildings b on  a.fwbh=b.fwbh where b.villagedm=@villagedm) b
";
                var sqlParams = new List<NpgsqlParameter>();
                sqlParams.Add(new NpgsqlParameter("villagedm", $"{villagedm}"));
                var tj = _dbContext.ZmPcGjzzCjTj.FromSqlRaw(sql.ToString(), sqlParams.ToArray()).FirstOrDefault();
                if (tj != null)
                {
                    from.Mzltlj = tj.Mzltlj;
                    from.Zzfasl = tj.Zzfasl;
                    from.Zzsgsl = tj.Zzsgsl;
                    from.Qcddzxcsl = tj.Qcddzxcsl;
                    from.Sjjzrksl = tj.Sjjzrksl;
                    from.Azgdjsbpsl = tj.Azgdjsbpsl;
                    from.Qlddzxcsl = tj.Qlddzxcsl;
                    from.Qlyhsyqpsl = tj.Qlyhsyqpsl;
                }
                var r = new RespRet<ZmPcGjzzCj>(true, "Ok", from);
                WriteSystemLog("housessqjz/search-gjzz", r, villagedm);
                return r;
            }
            catch (Exception ex)
            {
                var res = new RespRet<ZmPcGjzzCj>(false, ex.ToString());
                WriteSystemLogError("housessqjz/search-gjzz", res, villagedm);
                res.Msg = "系统异常";
                return res;
            }
        }








        /// <summary>
        /// 攻坚整治填报-村级
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("housessqjz/update-gjzztb")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<int>), 200)]
        public RespRet<int> Gjzztb([FromBody] ZmPcGjzzCjDto model)
        {
            var userNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet<int>(false, "user not logined");
            }
            try
            {
                var user = _dbContext.ZmUser.FirstOrDefault(c => c.Number == userNumber && c.IsDelete != 1 && c.Disabled != 1);
                var a = JsonRegion(user.District);
                JObject obj = JObject.Parse(user.District);
                string RegionCode = (string)obj["RegionCode"];
                if (RegionCode != model.Villagedm)
                {
                    var r1 = new RespRet<int>(false, "请传递正确的村代码");
                    WriteSystemLog("housessqjz/update-gjzztb", r1, model);
                    return r1;
                }
                var pc = _dbContext.ZmPcGjzzCj.AsNoTracking().FirstOrDefault(u => u.Villagedm == model.Villagedm);
                using (var transaction = _dbContext.Database.BeginTransaction())
                {
                    try
                    {
                        if (pc != null)
                        {
                            _dbContext.Remove(pc);
                            if (_dbContext.SaveChanges() == 0)
                            {
                                transaction.Rollback();
                                var r1 = new RespRet<int>(false, "操作失败");
                                WriteSystemLog("housessqjz/update-gjzztb", r1, model);
                                return r1;
                            }
                        }
                        model = _mapper.Map<ZmPcGjzzCjDto>(model);
                        var add = _mapper.Map<ZmPcGjzzCj>(model);
                        string sql = " select * from zm_building_ledger where villagedm=@villagedm ";
                        var region = _dbContext.ZmBuildingLedger.AsNoTracking().FirstOrDefault(u => u.villagedm == model.Villagedm);
                        if (region == null)
                        {
                            transaction.Rollback();
                            var r1 = new RespRet<int>(false, "未找到村庄，请检查村庄代码");
                            WriteSystemLog("housessqjz/update-gjzztb", r1, model);
                            return r1;
                        }
                        add.Xzq = region.xzq;
                        add.Xzqdm = region.xzqdm;
                        add.Town = region.town;
                        add.Towndm = region.towndm;
                        add.Village = region.village;
                        add.Villagedm = region.villagedm;
                        add.CreateBy = user.Number;
                        add.CreateName = user.Nickname;
                        add.Pcsj = DateTime.Now.ToString();
                        add.CreateOn = DateTime.Now;
                        add.Fj = string.IsNullOrWhiteSpace(model.Fj) ? null : JsonConvert.SerializeObject(add.Fj.Split("|"));
                        _dbContext.Add(add);
                        int i = _dbContext.SaveChanges();
                        if (i > 0)
                        {
                            ZmPcGjzzCjLog log = _mapper.Map<ZmPcGjzzCjLog>(add);
                            _dbContext.Add(log);
                            var res = _dbContext.SaveChanges();
                            if (res > 0)
                            {
                                transaction.Commit();
                                var r1 = new RespRet<int>(true, "操作成功", i);
                                WriteSystemLog("housessqjz/update-gjzztb", r1, model);
                                return r1;
                            }
                        }
                        transaction.Rollback();
                        var r = new RespRet<int>(false, "操作失败", i);
                        WriteSystemLog("housessqjz/update-gjzztb", r, model);
                        return r;
                    }
                    catch (Exception ex)
                    {
                        // 回滚事务
                        transaction.Rollback();
                        var res = new RespRet<int>(false, ex.ToString());
                        WriteSystemLogError("housessqjz/update-gjzztb", res, model);
                        res.Msg = "系统异常";
                        return res;
                    }
                }
            }
            catch (Exception ex)
            {
                var res = new RespRet<int>(false, ex.ToString());
                WriteSystemLogError("housessqjz/update-gjzztb", res, model);
                res.Msg = "系统异常";
                return res;
            }
        }




        /// <summary>
        /// 获取所有村庄
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("housessqjz/search-villagelist")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<ZmPcGjzzCj>), 200)]
        public RespRet<List<ZmVillage>> GetVillageList([FromQuery] string village)
        {
            try
            {

                string sql = @"select a.region_name village,b.region_name town,c.region_name xzq,a.region_code villagedm from zm_department a,zm_department b,
zm_department c where a.regional_level='7' and b.regional_level='6' and c.regional_level='5' and a.parent_id=b.region_code and b.parent_id=c.region_code and a.region_name like @village  ORDER BY a.region_code";
                var sqlParams = new List<NpgsqlParameter>();
                sqlParams.Add(new NpgsqlParameter("village", $"{"%" + village + "%"}"));
                var villagelist = _dbContext.ZmVillage.FromSqlRaw(sql.ToString(), sqlParams.ToArray()).ToList();

                var r = new RespRet<List<ZmVillage>>(true, "Ok", villagelist);
                WriteSystemLog("housessqjz/search-villagelist", r, village);
                return r;
            }
            catch (Exception ex)
            {
                var res = new RespRet<List<ZmVillage>>(false, ex.ToString());
                WriteSystemLogError("housessqjz/search-villagelist", res, village);
                res.Msg = "系统异常";
                return res;
            }
        }



        private byte[] GetDynamicVectorTile(int z, int x, int y)
        {
            var sql = @$"SELECT 
ST_AsMVT(P, 'ffpolygon', 4096, 'geom') AS tile 
FROM 
(SELECT 
ST_AsMVTGeom( ST_Transform(ST_SetSRID(geom, 4326), 3857), ST_TileEnvelope( {z}, {x}, {y}),4096,256,FALSE) AS geom, 
id,fwbh,yhfwbh,address
FROM zm_buildings_pc 
WHERE ST_Intersects(ST_SetSRID(geom, 4326), ST_Transform(ST_TileEnvelope( {z}, {x}, {y}), 4326))) AS P";
            var tile = _dbContext.Database.GetDbConnection().Query<byte[]>(sql).FirstOrDefault();
            return tile;
        }

        private byte[] GetDynamicVectorTile__build(int z, int x, int y)
        {





            var userNumber = this.CurrentUser();

            if (string.IsNullOrEmpty(userNumber))
            {
                return null;
            }
            var sql = "";
            var user = _userRepository.FirstOrDefault(u => u.Number == userNumber && u.IsDelete != 1 && u.Disabled != 1);
            var roleType = (PermissionRoleType)user.RoleType;
            var codeWhere = Utilitys.GetLikeSqlWhere_yt(user.Jurisdiction, null);
            if (roleType == PermissionRoleType.Admin || string.IsNullOrEmpty(codeWhere))
            {
                sql = @$"SELECT 
                ST_AsMVT(P, 'ffpolygon', 4096, 'geom') AS tile 
                FROM 
                (SELECT 
                ST_AsMVTGeom( ST_Transform(ST_SetSRID(geom, 4326), 3857), ST_TileEnvelope( {z}, {x}, {y}),4096,256,FALSE) AS geom, 
                ST_AsMVTGeom( ST_Transform(ST_SetSRID(geom, 4326), 3857), ST_TileEnvelope( 17, 107880, 49659),4096,256,FALSE) AS geom, 
                 zb.build_no,zb.build_name,zb.district_id,zb.district_name,zb.street_name,zb.street_id2021,zb.jcnd from  zm_yt_build  zb, zm_yt_buildmap zbm
                where zb.build_no =zbm.pfhouseid and ST_Intersects(ST_SetSRID(geom, 4326), ST_Transform(ST_TileEnvelope( {z}, {x}, {y}), 4326))) AS P";

            }
            else
            {

                if (!string.IsNullOrEmpty(codeWhere))
                {
                    sql = @$"SELECT 
                ST_AsMVT(P, 'ffpolygon', 4096, 'geom') AS tile 
                FROM 
                (SELECT 
                ST_AsMVTGeom( ST_Transform(ST_SetSRID(geom, 4326), 3857), ST_TileEnvelope( {z}, {x}, {y}),4096,256,FALSE) AS geom, 
                ST_AsMVTGeom( ST_Transform(ST_SetSRID(geom, 4326), 3857), ST_TileEnvelope( 17, 107880, 49659),4096,256,FALSE) AS geom, 
                 zb.build_no,zb.build_name,zb.district_id,zb.district_name,zb.street_name,zb.street_id2021,zb.jcnd from  zm_yt_build  zb, zm_yt_buildmap zbm
                where " + codeWhere + @$" and  zb.build_no =zbm.pfhouseid and ST_Intersects(ST_SetSRID(geom, 4326), ST_Transform(ST_TileEnvelope( {z}, {x}, {y}), 4326))) AS P";

                }

            }

            var tile = _dbContext.Database.GetDbConnection().Query<byte[]>(sql).FirstOrDefault();
            return tile;



        }


        private byte[] GetRiskHouseDynamicVectorTile(int z, int x, int y)
        {
            var sql = @$"SELECT 
ST_AsMVT(P, 'ffpolygon', 4096, 'geom') AS tile 
FROM 
(SELECT 
ST_AsMVTGeom( ST_Transform(ST_SetSRID(geom, 4326), 3857), ST_TileEnvelope( {z}, {x}, {y}),4096,256,FALSE) AS geom,fwyt, 
id,fwbh,yhfwbh,address,result,city_result as cityResult,aqyhcp 
FROM risk_census_house_yhpc 
WHERE ST_Intersects(ST_SetSRID(geom, 4326), ST_Transform(ST_TileEnvelope( {z}, {x}, {y}), 4326))) AS P";
            var tile = _dbContext.Database.GetDbConnection().Query<byte[]>(sql).FirstOrDefault();
            return tile;
        }

        private FileInfo ConvertFormFileToFileInfo(IFormFile formFile, out string path)
        {
            // 创建一个临时文件路径
            string tempFilePath = System.IO.Path.GetTempFileName();

            // 使用 IFormFile 对象的 OpenReadStream() 方法来获取文件流
            using (var stream = new FileStream(tempFilePath, FileMode.Create))
            {
                formFile.CopyTo(stream);
            }

            // 创建 FileInfo 对象
            FileInfo fileInfo = new FileInfo(tempFilePath);
            path = fileInfo.FullName;
            return fileInfo;
        }









        [HttpGet("getfile")]
        public async Task<IActionResult> getfile(string key)
        {
            var file = _kS3Client.getObject("xfpc-test", key);//"c1d276ab-f3a8-4936-9aab-d6a12c77a03c");
            var ObjectContent = file.getObjectContent();
            StreamReader sr = new StreamReader(ObjectContent);
            var ObjectMetadata = file.getObjectMetadata();
            //StreamReader sr = new StreamReader(file.getObjectContent());
            var filebyte = ConvertStreamReaderToByteArray(sr);

            string img = Convert.ToBase64String(filebyte);
            // 返回文件路径
            //return File(filebyte, "image/png", key );
            return Ok(new { imagePath = img });
        }
        //[HttpGet("getfile")]
        //public async Task<IActionResult> getfile(string key)
        //{
        //    // 获取后缀名
        //    var extension = Path.GetExtension(key).ToLower();
        //    // 获取mimetype
        //    var mine = "image/" + extension.Substring(1, extension.Length - 1);
        //    var file = _kS3Client.getObject("xfpc-test", key);
        //    // 把Content转成byte返回
        //    var filebyte = file.getObjectContent().ReadAsBytes();
        //    // 返回文件路径
        //    return File(filebyte, mine, key);
        //}

        private byte[] ConvertStreamReaderToByteArray(StreamReader reader)
        {
            // 使用 MemoryStream 来存储字节数据
            using (MemoryStream memoryStream = new MemoryStream())
            {
                // 将 StreamReader 的内容复制到 MemoryStream 中
                using (StreamWriter streamWriter = new StreamWriter(memoryStream))
                {
                    streamWriter.Write(reader.ReadToEnd());
                    streamWriter.Flush();
                }

                // 将 MemoryStream 转换为字节数组
                byte[] byteArray = memoryStream.ToArray();

                return byteArray;
            }
        }

    }
}